TypeScript:构造函数中的约束

时间:2019-09-24 13:58:11

标签: typescript

ExclusiveValues是类似于单选按钮的数据结构。

type FilteredProperty<T,U> = {[K in keyof T]: T[K] extends U ? K : never}[keyof T];

class ExclusiveValues<T,U> {
  private currentActiveObject: T|null = null;

  constructor(
    private propertyName: FilteredProperty<T,U>,
    private targetArray: T[],
    private activeValue: T[FilteredProperty<T,U>],
    private defaultValue: T[FilteredProperty<T,U>]) {}

  setActive(target: T) {
    if(this.currentActiveObject != null) {
      this.currentActiveObject[this.propertyName] = this.defaultValue;
    }
    target[this.propertyName] = this.activeValue;
    this.currentActiveObject = target;
  }
}

第一种情况

//ok
const test = new ExclusiveValues<target,boolean>("PropertyA",sampleArray,true,false);

第二种情况错误!

class ExclusiveBooleanValues<T> extends ExclusiveValues<T,boolean> {
  constructor(propertyName: FilteredProperty<T,boolean>,targetArray: T[]) {
    //Error!! Argument of type 'true' is not assignable to parameter of type 'T[{ [K in keyof T]: T[K] extends boolean ? K : never; }[keyof T]]'.
    super(propertyName,targetArray,true,false); 
  }
}

我不知道为什么它不起作用... 为什么?

this is playground code

0 个答案:

没有答案
相关问题