When I type in the chrome dev tools:
"1".padStart(2,0)
I get
"01"
But when I write
"1".padStart(2,0)
in my typescript project
I get
Property 'padStart' does not exist on type 'string'.
Why does Typescript complain? How do I fix this?
The "padStart is not a function" error occurs when we call the padStart() method on a value that is not a string. To solve the error, convert the value to a string using the toString() method or make sure to only call the padStart method on strings.
padStart is defined in the ES2017 standard. You need to tell typescript to use the apropriate typings (the ones for ES2017 ). You can do this either by setting the target to ES2017 , if your runtime supports all the language features required by ES2017 (which is probably not the case at the time of writing).
padStart
is defined in the ES2017
standard. You need to tell typescript to use the apropriate typings (the ones for ES2017
). You can do this either by setting the target to ES2017
, if your runtime supports all the language features required by ES2017
(which is probably not the case at the time of writing).
Another option is to just set the libs
option in order to get the typings for runtime objects in accordance with ES2017
but still compile down to whatever language version you are targeting.(Note that the runtime itself needs to support padStart
, typescript will not provide any poly-fills)
You can do this in tsconfig
using the lib
option:
"compilerOptions": { "target": "es2016", "lib": [ "es2017", "dom" "scripthost" ], // ... }
You can read more about lib vs target in this answer
To make TypeScript aware of String.prototype.padStart(), you need to specify es2017
in the list of libraries in your tsconfig.json
. If you do that, then TypeScript will assume that all the ES2017 features can be used which might not be exactly what you want.
Platforms like Node.js don't always implement the complete feature set of a new ECMAScript language specification, so it's safer to only add the language features where you are confident that they exist. If you are not sure which features are supported by your targeted platform, you can look them up on pages likes node.green or MDNs browser compatibility list.
The padStart
function is part of the String prototype, so it is sufficient to just add es2017.string
in your tsconfig.json
:
{ "compilerOptions": { "lib": ["es6", "es2017.string"], ... }, }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With