Свойства проверки типов, динамически создаваемые с помощью 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;

он по-прежнему компилируется, хотя, вероятно, не должен. Итак, мой вопрос: есть ли способ проверить такие динамически созданные свойства? Я бы предположил, что если это жестко запрограммированная строка, такая как «длина», тогда это было бы возможно.

Вот мои 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"
  ]
}

person Community    schedule 18.07.2018    source источник


Ответы (1)


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

} 
person basarat    schedule 18.07.2018