Reputation: 2121
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:
Upvotes: 1
Views: 16606
Reputation: 17858
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);}
Upvotes: 2