小编Csv*_*svn的帖子

使用属性装饰器严格检查属性类型

有没有一种方法可以验证Typescript中装饰的属性的类型?我想要一个仅适用于boolean类属性,而不适用于例如string(下面的示例)的属性装饰器。这可能吗?

(注意:我不希望通过reflect-metadata进行运行时验证,而只是使用Typescript进行编译类型警告。)

function booleanProperty<T extends HTMLElement>(target: T, prop: string) {
  // `target` will be the class' prototype
  Reflect.defineProperty(target, prop, {
    get(this: T): boolean {
      return this.hasAttribute(prop);
    },
    set(this: T, value: boolean): void {
      if (value) {
        this.setAttribute(prop, '');
      } else {
        this.removeAttribute(prop);
      }
    }
  });
}

class MyElement extends HTMLElement {
  @booleanProperty
  foo: boolean;

  @booleanProperty
  bar: string; // TS compile error
}
customElements.define('my-element', MyElement);
Run Code Online (Sandbox Code Playgroud)

decorator web-component typescript

2
推荐指数
1
解决办法
446
查看次数

标签 统计

decorator ×1

typescript ×1

web-component ×1