How to extend a primitive type in typescript?
Asked Answered
S

2

4

I want to create an interface like this:

interface Show {
  show(): string;
}

function doit(s: Show) {
  return 'Showed: ' + s.show();
}

Then we can use it with a new class:

class Foo {
  s: string;
  constructor(s: string) { 
    this.s = s; 
  }
  show() {
    return 'Foo with "' + this.s + '"';
  }
}

console.log(doit(new Foo('hello')));

I'd like to do the same thing for Numbers. In plain JavaScript I could make the type Number, for example, satisfy this interface with:

Number.prototype.show = function() { 
  return '' + this; 
}

But TypeScript doesn't let me do this:

show.ts(18,18): error TS2094: The property 'show' does not exist on value of type 'Number'.

Is there a way to do this?

Stokeontrent answered 26/4, 2014 at 4:15 Comment(0)
A
5

Just tell TypeScript about it by adding to Number :

interface Number{
    show():string;
}

Number.prototype.show = function() { 
  return '' + this; 
}

var foo = 123;
foo.show();

Please note that even tough it is supported it is considered bad practice to do so even in JavaScript land : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes

Al answered 26/4, 2014 at 5:2 Comment(0)
T
0
interface Number {
    show(): string
}

Number.prototype.show = function (){
    return this + 'Show me'
}

const qwe = 1
qwe.show()
Tabathatabb answered 12/3, 2024 at 11:8 Comment(1)
Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.Doerrer

© 2022 - 2025 — McMap. All rights reserved.