Typescript - How do I add an extension method

后端 未结 2 1000
长情又很酷
长情又很酷 2021-01-16 08:07

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

相关标签:
2条回答
  • 2021-01-16 08:42

    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();
    
    0 讨论(0)
  • 2021-01-16 09:00

    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

    0 讨论(0)
提交回复
热议问题