我有以下课程:
export class SomeModel {
prop1: number;
prop2: number;
comment: string;
}
以及以下动态获取其属性的方法:
getTypeProperties<T>(obj: T): string[] {
const ret: string[] = [];
for (const key in obj) {
if (obj.hasOwnProperty(key))
ret.push(key);
}
return ret;
}
以下调用返回一个空数组:
getTypeProperties(new SomeModel());
但是,如果我用 显式初始化所有属性null
,则将正确返回属性:
export class SomeModel {
prop1: number = null;
prop2: number = null;
comment: string = null;
}
问题:这是正常行为吗?或者是否有一个 TypeScript 编译器开关来切换它?
我不知道它是否相关,但这里是 tsconfig.json 内容:
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}