问题
I read that you can create extension methods in Typescript and I looked up some code
And put that code in my extension methods.ts but I get an error saying that toNumber doesn't exist. How can I fix this?
回答1:
You can extend String
interface by augmenting global scope:
export { };
declare global {
interface String {
toNumber(): number;
}
}
String.prototype.toNumber = function (this: string) { return parseFloat(this) };
Playground
回答2:
You could extend the String
interface, like this:
interface String {
toNumber(): number;
}
String.prototype.toNumber = function(this: string) {
return parseFloat(this);
}
const s = '123.45';
s.toNumber();
来源:https://stackoverflow.com/questions/59089145/typescript-how-do-i-add-an-extension-method