Typescript - How do I add an extension method

妖精的绣舞 提交于 2019-12-11 07:21:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!