使用 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
进行类型检查。
候补
你实际上可以定义一个 getter 编译成同样的东西
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;
}
}
我有这样一个方便的结构:
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
进行类型检查。
候补
你实际上可以定义一个 getter 编译成同样的东西
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;
}
}