问题描述
我有一个JavaScript对象,它动态地允许成员作为访问者属性绑定到对象的实例:
I have a JavaScript object which dynamically allows members to be bound as accessor properties to instances of the object:
来源
function DynamicObject(obj) {
for (var prop in obj) {
Object.defineProperty(this, prop, {
get: function () { return obj[prop]; },
set: function (value) { obj[prop] = value; },
enumerable: true,
configurable: false
});
}
}
用法
var obj = new DynamicObject({
name: "John Smith",
email: "[email protected]",
id: 1
});
创建 obj
时,成员构造函数参数作为访问者属性绑定到 obj
。这些显示在intellisense中
When obj
is created, the members of the constructor parameter are bound to obj
as accessor properties. These show up in intellisense
我想要知道是否有可能在TypeScript中对这种行为进行建模(包括智能感知)?
I would like to know if it is possible to model this sort of behavior (including having intellisense) in TypeScript?
注释
当您在TypeScript中运行此代码时,没有智能感知,因为一切都是任何
,因此TypeScript并不真正知道发生了什么。
When you run this code in TypeScript, there is no intellisense becuase everything is any
, so TypeScript doesn't really know what's going on.
推荐答案
是。
您可以将通用调用签名分配给 DynamicObject
。您需要将其声明为变量:
You can assign a generic call signature to DynamicObject
. You'll need to declare it as a variable:
var DynamicObject: new <T>(obj: T) => T = function (obj)
{
for (var prop in obj)
{
Object.defineProperty(this, prop, {
get: function () { return obj[prop]; },
set: function (value) { obj[prop] = value; },
enumerable: true,
configurable: false
});
}
} as any;
这样,IntelliSense将处理从新DynamicObject $返回的值c $ c>与传入的值具有相同的类型。相同的属性名称,相同的属性类型。您将获得完全自动完成和类型安全。
This way, IntelliSense will treat the value returned from new DynamicObject
as having the same type as the value passed in. Same property names, same property types. You'll get full autocomplete and type-safety.
如果您在第一行中缠绕头部时遇到困难,则与编写以下内容相同:
// Declare type (only exists during compile-time)
var DynamicObject: new <T>(obj: T) => T;
// Assign value (during runtime)
DynamicObject = function (obj)
{
...
} as any;
这篇关于JavaScript到TypeScript:Intellisense和动态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!