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

Strict type checking for property type with property decorator

有没有办法验证在 Typescript 中修饰的 属性 的类型?我想要一个 属性 装饰器,它只适用于 boolean class 属性,但不适用于例如string(下例)。这可能吗?

(注意:我不想通过反射元数据进行运行时验证,只是使用 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);

这个呢?

function booleanProperty<
  T extends HTMLElement & Record<K, boolean>,
  K extends string>(target: T, prop: K) {
    // ... impl here
}

传入的 target 需要是一个 HTMLElement,它在键 K 处有一个 boolean 属性,其中 K 是传入的类型 prop。让我们看看它是否有效:

class MyElement extends HTMLElement {
  @booleanProperty // okay
  foo: boolean;

  @booleanProperty // error
  bar: string;
}

我觉得不错。这对你有用吗?