[英]How to create value properties in TypeScript
TypeScript has a built in feature for defining accessor properties TypeScript具有用于定义访问器属性的内置功能
class Test {
constructor(private value: number = 123) {
}
public get Value(): number {
return this.value;
}
public set Value(value: number) {
this.value = value;
}
}
Compiler output 编译器输出
var Test = (function () {
function Test(value) {
if (value === void 0) { value = 123; }
this.value = value;
}
Object.defineProperty(Test.prototype, "Value", {
get: function () {
return this.value;
},
set: function (value) {
this.value = value;
},
enumerable: true,
configurable: true
});
return Test;
})();
JavaScript also supports value properties JavaScript还支持值属性
Object.defineProperty(someObj, "MyValueProperty", {
// The key here is value as opposed to get and set.
value: 5
enumerable: true,
configurable: false
});
How do you define value propertes with TypeScript? 如何使用TypeScript定义值属性?
NOTICE: I notice that I'm being pointed to another stackoverflow question regarding TypeScript getters and setters. 注意:我注意到我被指向另一个与TypeScript吸气剂和吸气剂有关的stackoverflow问题。 This is not what I want.
这不是我想要的。 I want to know how to create properties that implement
value
, not get
and set
! 我想知道如何创建实现
value
属性, 而不是 get
和set
!
You could do the following: 您可以执行以下操作:
class Test {
Value : number;
}
Object.defineProperty(Test.prototype, "Value", {
value: 5,
enumerable: true,
configurable: false
});
var t = new Test();
t.Value = 54;
console.log(t.Value); // 5
But why not just return the value in the get function? 但是,为什么不只返回get函数中的值呢?
class Test {
public get Value(): number {
return 5;
}
}
var t = new Test();
t.Value = 54;
console.log(t.Value); // 5
Using Decorators 使用装饰器
A more elegant way if you really want a value property is to create a reusable decorator: 如果您确实想要一个value属性,一种更优雅的方法是创建一个可重用的装饰器:
function ValueProperty(value: any) {
return (target: Object, propertyKey: string) => {
Object.defineProperty(target, propertyKey, {
value,
enumerable: true,
configurable: false
});
};
}
Then to use it: 然后使用它:
class Test {
@ValueProperty(5)
Value: number;
}
new Test().Value; // 5
Typescript does not support that currently. Typescript目前不支持。 Looking at the language specification and the
Emitter
class of the typescript compiler i couldn't find anything indicating that value properties are supported. 查看语言规范和打字稿编译器的
Emitter
类,我找不到任何表明支持值属性的内容。
https://github.com/Microsoft/TypeScript/blob/9a89147587c06ba51181ff2ee5ade69a98b171ea/src/services/compiler/emitter.ts#L2402 https://github.com/Microsoft/TypeScript/blob/9a89147587c06ba51181ff2ee5ade69a98b171ea/src/services/compiler/emitter.ts#L2402
I guess that your only option is to use raw Javascript and Object.defineProperty
to define them. 我猜您唯一的选择是使用原始Javascript和
Object.defineProperty
来定义它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.