我问了几个与扩展 JavaScript 中现有对象的静态功能(使用 TypeScript)相关的问题。为了这里的所有示例,我使用 Object
以下代码演示了 ECMAScript 的 Object.is
函数的 polyfill 定义
Object.is = function(value1: any, value2: any): boolean {
// ....impl
}; // ERROR : Property 'is' does not exist on type...
这是因为is
还没有在Object
上实现,但是我们可以像这样让它可见
declare var Object: {
is(value1: any, value2: any): boolean;
}
但是,此代码的问题在于,它会覆盖任何现有的静态绑定(bind)(bind
、call
、create
、freeze
等)。
据我了解,使用最新版本的 TypeScript,我们现在可以将开放式接口(interface)静态绑定(bind)到对象声明:
interface _Object {
is(value1: any, value2: any): boolean;
}
declare var Object: _Object;
这很棒,因为正如所指出的,TypeScript 中的接口(interface)是开放式的,因此我可以不断地将越来越多的功能绑定(bind)到 Object
中,但这并不能解决一旦绑定(bind)接口(interface)的问题到Object
,它会覆盖现有的声明,因为lib.d.ts仍然像这样声明 Object
:
declare var Object: {
new (value?: any): Object;
(): any;
(value: any): any;
prototype: Object;
getPrototypeOf(o: any): any;
getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor;
getOwnPropertyNames(o: any): string[];
create(o: any, properties?: PropertyDescriptorMap): any;
defineProperty(o: any, p: string, attributes: PropertyDescriptor): any;
defineProperties(o: any, properties: PropertyDescriptorMap): any;
seal(o: any): any;
freeze(o: any): any;
preventExtensions(o: any): any;
isSealed(o: any): boolean;
isFrozen(o: any): boolean;
isExtensible(o: any): boolean;
keys(o: any): string[];
}
我觉得 lib.d.ts 中的代码需要什么进行重构以允许开放式接口(interface)静态绑定(bind)到声明,就像这样
interface _Object {
new (value?: any): Object;
(): any;
(value: any): any;
prototype: Object;
getPrototypeOf(o: any): any;
getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor;
getOwnPropertyNames(o: any): string[];
create(o: any, properties?: PropertyDescriptorMap): any;
defineProperty(o: any, p: string, attributes: PropertyDescriptor): any;
defineProperties(o: any, properties: PropertyDescriptorMap): any;
seal(o: any): any;
freeze(o: any): any;
preventExtensions(o: any): any;
isSealed(o: any): boolean;
isFrozen(o: any): boolean;
isExtensible(o: any): boolean;
keys(o: any): string[];
}
declare var Object: _Object;
因此,当我为 Object.is
创建接口(interface)及其附带功能时,一切都应该协调一致<---请原谅双关语,(ECMAScript 6 代码名称)
我想知道的是,TypeScript future 版本是否有任何计划可以按照建议解决此问题(或者实际上有任何证明更有效的修复)?
最佳答案
自 TypeScript 1.4 起,可以轻松添加静态扩展。 TypeScript 团队更改了 lib.d.ts
文件,以对所有静态类型定义使用接口(interface)。
静态类型定义的命名方式都类似于[Type]Constructor
:因此,如果您想向Object
类型添加静态函数,请将您的定义添加到对象构造函数
。
定义:
interface ObjectConstructor
{
is(value1: any, value2: any): boolean;
}
实现:
Object.is = function(value1: any, value2: any): boolean
{
// your implementation here
}
关于javascript - TypeScript 静态接口(interface)绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27144550/