TypeScript:扩充内置类型

Spo*_*man 14 typescript

如何增加"内置"类型之一?例如阵列?

在JS中,我会做类似的事情

Array.prototype.shuffle = function () { ... };
Run Code Online (Sandbox Code Playgroud)

什么是TypeScript的等价物?

Bil*_*rst 20

类型在TypeScript中是"开放式的",因此您只需编写:

interface Array {
  shuffle: () => any; // <-- Whatever signature you want.
}
Run Code Online (Sandbox Code Playgroud)

然后扩展类型以包含新函数(并且可以为其分配与签名匹配的函数).

但请注意,扩展内置类型(lib.d.ts中的那些类型 - 例如Array)在语言服务中当前存在问题,因为它在内部缓存这些因为性能原因.我在http://typescript.codeplex.com/workitem/4上编写的解决方法是为了在VS中的语言服务中扩展内置类型而没有错误.

  • 我们可以链接到解决方案吗? (2认同)