1

I am trying to add extension method to String in typescript. Please help me to solve the below compile error.

I have added the below code in string-extensions.ts file in reactjs project.

declare global {  
    interface String {
        toNumber(): number;
    }
}  

String.prototype.toNumber = function() { return parseFloat(this);}

export {};

I am getting the error: Argument of type 'String' is not assignable to parameter of type 'string'. 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible. TS2345

I tried the below code on typescript compiler. It runs and display the output but it also gives the compiler error: enter image description here enter image description here

Ayaz
  • 2,111
  • 4
  • 13
  • 16

1 Answers1

2

As the error mentions that String is a wrapper object by TS and that parseFloat accepts the first parameter as string.

As for workarounds, you can do one of the following;

String.prototype.toNumber = function() { return parseFloat(this.toString());}

// or
String.prototype.toNumber = function() { return parseFloat(this as string);}
choz
  • 17,242
  • 4
  • 53
  • 73
  • 1
    Not sure why I escalated my edit to ESLint, thanks for pointing that out @AluanHaddad – choz Jan 22 '21 at 16:42
  • 1
    Thanks Choz. It's working. I was in assumption that string and String are same. Well explaned on difference between string and String. https://stackoverflow.com/questions/14727044/typescript-difference-between-string-and-string – Ayaz Jan 22 '21 at 16:54