0

I need to add my own method into a string in typescript. so hopefully I can do something like this

const myPoint : string = "23";
const customNumber = myPoint.convertUsingMyCustomImplementation();

I try this (using capital S) :

// eslint-disable-next-line no-extend-native
String.prototype.convertUsingMyCustomImplementation = function() : number {
  return parseFloat(this);
};

but I have two errors

enter image description here

Property 'convertUsingMyCustomImplementation' does not exist on type 'String'.

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.

and I also try the code below:

// eslint-disable-next-line no-extend-native
string.prototype.convertUsingMyCustomImplementation = function() : number {
  return parseFloat(this);
};

but I also have an error

enter image description here

how to achieve that using Typescript?

sarah
  • 3,819
  • 4
  • 38
  • 80
  • What happened when you used `String.prototype` and `String: this` ? Did you try that yet? (I don't use typescript) – enhzflep Mar 22 '21 at 03:36
  • Does this answer your question? [How to extend String Prototype and use it next, in Typescript?](https://stackoverflow.com/questions/39877156/how-to-extend-string-prototype-and-use-it-next-in-typescript) – esqew Mar 22 '21 at 03:40

1 Answers1

0

Your prototype method was fine. You just have to declare that string will have this method. Usually you do this in a .d.ts file to allow it to work everywhere, but you can do it in a regular ts file in a pinch.

declare global { 
    interface String { 
        convertUsingMyCustomImplementation(): number;
    } 
}
Tim
  • 2,878
  • 1
  • 14
  • 19