![](/img/trans.png)
[英]Ensure spyOnProperty creates configurable properties with Object.defineProperty
[英]Type-checking properties created dynamically with Object.defineProperty
我有这样方便的构造:
export class LinkedQueue {
private lookup = new Map<any, any>();
private head = null as any;
private tail = null as any;
public length: number;
constructor() {
Object.defineProperty(this, 'length', {
get: () => {
return this.lookup.size;
}
});
}
}
请注意,如果我删除此行:
public length: number;
它仍然可以编译,即使它可能不应该编译。 所以我的问题是-有没有办法键入检查像这样动态创建的属性? 我会假设它是一个像'length'这样的硬编码字符串,那么这是有可能的。
这是我的tsconfig.json
设置:
{
"compilerOptions": {
"outDir":"dist",
"allowJs": false,
"pretty": true,
"skipLibCheck": true,
"declaration": true,
"baseUrl": ".",
"target": "es6",
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"allowUnreachableCode": true,
"lib": [
"es2015",
"es2016",
"es2017"
]
},
"compileOnSave": false,
"exclude": [
"test",
"node_modules"
],
"include": [
"src"
]
}
Object.defineProperty(this, 'length', {
类型进行类型检查,以检查其如何使this
突变。
您实际上可以定义一个可编译为同一事物的吸气剂
export class LinkedQueue {
private lookup = new Map<any, any>();
private head = null as any;
private tail = null as any;
constructor() {
}
get length() {
return this.lookup.size;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.