ts如何声明类的泛型

redbuck
  • 2.4k

我有如下一个类:

class Test {
  value: number | number[];

  constructor(value: number | number[]) {
    this.value = value;
  }

  get computedValue() {
    if (typeof this.value === 'number') return this.value * 2;
    if (Array.isArray(this.value)) return this.value.map(i => i * 2);
  }
}

计算属性computedValue的类型是由实例对象时传入参数决定的.

const test = new Test(1)

const value:number = test.computedValue 
// 报错->'number[]' is not assignable to type 'number'.

这种应该是用泛型吧.但我对泛型不熟,再一个取值函数似乎无法声明类型.

我尝试了声明一个interface,然后类再实现这个interface的方式也不行.



进阶:

如果constructor接受一个配置对象,value是其中的一个属性,那又要如何声明呢?

望大佬们不啬赐教~~

update

查阅文档后更改如下,但依然报错

type TestProps = number | number[]

class Test<T extends TestProps> {
  constructor(value: T) {
    this.value = value;
  }

  value: T;

  get computedValue(): T {
    if (typeof this.value === 'number') {
      return this.value * 2;
// error->Type 'number' is not assignable to type 'T'.
    }
    if (Array.isArray(this.value)) {
      return this.value.map(i => i * 2);
// error->Type 'number[]' is not assignable to type 'T'.
    }
  }
}

const test = new Test<number>(1);
const test2 = new Test<number[]>([1, 2]);

const num1: number = test.computedValue;
const num2: number[] = test2.computedValue;
回复
阅读 889
2 个回答
get computedValue(): T {
    if (Array.isArray(this.value)) {
      return this.value.map(i => i * 2) as T
    } else {
      return ((this.value as number) * 2) as T
    }
}

你这个类不是泛型,你如果只是想简单解决这个问题,可以把computedValue的类型设置为any:

  get computedValue():any {
    if (typeof this.value === 'number') return this.value * 2;
    if (Array.isArray(this.value)) return this.value.map(i => i * 2);
  }

然后

const value:number = test.computedValue as number;
就可以

其实也可以这样:

  get computedValue():number|number[] {
    if (typeof this.value === 'number') return this.value * 2;
    if (Array.isArray(this.value)) return this.value.map(i => i * 2);
  }

const value:number = test.computedValue as number;

你知道吗?

宣传栏