有没有办法查明接口(interface)的属性是否定义为只读?说,
interface ITest {
readonly foo: number;
}
现在,TypeScript 是否有某种反射或诡计来获取此信息?例如。像这样的东西:
let info = Reflect.get(ITest, 'foo');
if (info.isReadOnly()) { ... }
最佳答案
由于 TypeScript 接口(interface)在运行时不存在,因此您不能对它们使用反射。为了使用反射,我创建了一个实现接口(interface)并反射(reflect)在类上的类。但是,我无法判断一个属性是否是只读的。不确定这是我的理解不足还是缺陷。这是我尝试过的:
代码
interface ITest {
readonly foo: number;
bar: number;
}
class TestImplementation implements ITest {
readonly foo: number = 1;
bar: number = 2;
}
function reflectOnTest() {
var testImplementation = new TestImplementation();
var properties: string[] = Object.getOwnPropertyNames(testImplementation);
var fooDescriptor = Object.getOwnPropertyDescriptor(testImplementation, properties[0]);
var barDescriptor = Object.getOwnPropertyDescriptor(testImplementation, properties[1]);
console.log("foo writable = " + fooDescriptor.writable);
console.log("bar writable = " + barDescriptor.writable);
}
输出是:
foo writable = true
酒吧可写=真
关于接口(interface)的 TypeScript 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41564078/