【问题标题】:Type-checking properties created dynamically with Object.defineProperty使用 Object.defineProperty 动态创建的类型检查属性
【发布时间】:2018-07-18 00:51:30
【问题描述】:

我有这样方便的构造:

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

【问题讨论】:

    标签: typescript tsc


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2022-01-19
      • 2020-01-08
      • 2019-05-02
      • 2020-06-02
      • 1970-01-01
      相关资源
      最近更新 更多