TypeScript:增加内置类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12701732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript: augmenting built-in types
提问by Spongman
how does one augment one of the 'built-in' types? eg Array?
如何增加一种“内置”类型?例如数组?
In JS, I'd do something like
在 JS 中,我会做类似的事情
Array.prototype.shuffle = function () { ... };
what's the equivalent in TypeScript?
TypeScript 中的等价物是什么?
回答by Bill Ticehurst
Types are 'open ended' in TypeScript, so you can just write:
TypeScript 中的类型是“开放式”的,所以你可以这样写:
interface Array {
shuffle: () => any; // <-- Whatever signature you want.
}
And then the type is expanded to include the new function (and you can assign a function matching the signature to it).
然后类型被扩展以包含新函数(并且您可以为其分配与签名匹配的函数)。
Note however that extending the built-in types (those in lib.d.ts - such as Array) has an issue currently in the language service, as it caches those internally for perf reasons. Do the workaround I wrote-up at http://typescript.codeplex.com/workitem/4to extend the built-in types without errors in the language service in VS.
但是请注意,扩展内置类型(lib.d.ts 中的那些 - 例如 Array)在语言服务中存在一个问题,因为它出于性能原因在内部缓存这些。执行我在http://typescript.codeplex.com/workitem/4上写的解决方法,以扩展内置类型而不会在 VS 的语言服务中出错。

