mercredi 27 juin 2018

Uninitialized TypeScript class properties are not iterated

I have the following class:

export class SomeModel {
  prop1: number;
  prop2: number;
  comment: string;
}

and the following method to dynamically get its properties:

getTypeProperties<T>(obj: T): string[] {
    const ret: string[] = [];
    for (const key in obj) {
      if (obj.hasOwnProperty(key))
        ret.push(key);
    }
    return ret;
}

The following call returns an empty array:

getTypeProperties(new SomeModel());

However, if I explicitly initialize all properties with null, the properties will be returned correctly:

export class SomeModel {
  prop1: number = null;
  prop2: number = null;
  comment: string = null;
}

Question: Is this normal behavior? Or is there a TypeScript compiler switch to toggle this?

I do not know if it is relevant, but here is the tsconfig.json content:

{
  "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"
    ]
  }
}





Aucun commentaire:

Enregistrer un commentaire