如何从构造函数中的可选参数推断泛型类型

时间:2021-05-17 16:28:01

标签: javascript typescript

我试图在构造函数中有一个可选参数,其类型被推断为属性的类型。不幸的是,当没有传递参数时,Typescript 决定类型是“未知”而不是推断类型是“未定义”:

class Example<Inner> {
  inner: Inner;

  constructor(inner?: Inner) {
    if (inner) {
      this.inner = inner;
    }
  }
}

const a = new Example('foo'); // const a: Example<string>
const b = new Example(); // const b: Example<unknown>

有没有办法解决这个问题,而不必指定泛型类型或参数?

我尝试改用默认值:constructor(inner: Inner = undefined) {,但随后出现错误:

<块引用>

类型 'undefined' 不能分配给类型 'Inner'。 'Inner' 可以用与 'undefined' 无关的任意类型实例化。ts(2322)`

1 个答案:

答案 0 :(得分:0)

= undefined 添加到泛型类型修复了问题:

class Example<Inner = undefined> {
  inner: Inner;

  constructor(inner?: Inner) {
    if (inner) {
      this.inner = inner;
    }
  }
}

const a = new Example('foo'); // const a: Example<string>
const b = new Example(); // const b: Example<undefined>

感谢 Nadia Chibrikovacomments 中的建议:

<块引用>

试试 class Example { inner?: Inner; ...?