简体   繁体   中英

Type-checking properties created dynamically with Object.defineProperty

I have this handy construct like so:

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;
      }
    });

  }

} 

note that if I remove this line:

 public length: number;

it still compiles, even though it probably shouldn't. So my question is - is there a way to type check dynamically created properties like that? I would assume if it's a hardcoded string like 'length', then it would be possible.

Here are my tsconfig.json settings:

{
  "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', { is not type checked for how its mutating this .

Alternate

You can actually define a getter that compiles to the same thing

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;
  } 

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM