如何在打字稿中扩展原始类型? [英] How to extend a primitive type in typescript?

查看:97
本文介绍了如何在打字稿中扩展原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个这样的界面:

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')));

我想对数字秒。在纯JavaScript中我可以使类型 Number ,例如,满足此接口:

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; 
}

但TypeScript不允许我这样做:

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?

推荐答案

只需通过添加数字告诉TypeScript:

Just tell TypeScript about it by adding to Number :

interface Number{
    show():string;
}

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

var foo = 123;
foo.show();

请注意,即使在JavaScript版本中,即使在强大的版本支持下也是如此。 https://developer.mozilla.org/en -US / docs / Web / JavaScript / Guide / Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes

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

这篇关于如何在打字稿中扩展原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆