Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript tells me property 'padStart' does not exist on type 'string'. Why?

Tags:

typescript

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?

like image 982
user1283776 Avatar asked Sep 12 '18 10:09

user1283776


People also ask

Why is padStart not working?

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.

How do I use padStart typescript?

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).


Video Answer


2 Answers

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

like image 95
Titian Cernicova-Dragomir Avatar answered Sep 18 '22 17:09

Titian Cernicova-Dragomir


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"],     ...   }, } 
like image 22
Benny Neugebauer Avatar answered Sep 19 '22 17:09

Benny Neugebauer