TypeScript:增加内置类型 [英] TypeScript: augmenting built-in types

查看:40
本文介绍了TypeScript:增加内置类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何扩充其中一种内置"类型?例如数组?

how does one augment one of the 'built-in' types? eg Array?

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

In JS, I'd do something like

Array.prototype.shuffle = function () { ... };

TypeScript 中的等价物是什么?

what's the equivalent in TypeScript?

推荐答案

类型在 TypeScript 中是开放式"的,所以你可以这样写:

Types are 'open ended' in TypeScript, so you can just write:

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).

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

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/4 to extend the built-in types without errors in the language service in VS.

这篇关于TypeScript:增加内置类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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