Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - How do I add an extension method

I read that you can create extension methods in Typescript and I looked up some code

enter image description here

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?

like image 273
anonymous-dev Avatar asked Sep 21 '25 03:09

anonymous-dev


1 Answers

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

like image 169
Aleksey L. Avatar answered Sep 22 '25 19:09

Aleksey L.