简体   繁体   English

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

[英]How to infer generic type from an optional parameter in a constructor

I'm trying to have an optional parameter in a constructor, whose type is inferred as the type of a property.我试图在构造函数中有一个可选参数,其类型被推断为属性的类型。 Unfortunately when the argument is not passed, Typescript decides the type is "unknown" rather than inferring the type is "undefined":不幸的是,当参数未传递时,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>

Is there a way around this without having to specify the generic type or the argument?有没有办法解决这个问题而不必指定泛型类型或参数?

I tried using a default value instead: constructor(inner: Inner = undefined) { , but then I get the error:我尝试改用默认值: constructor(inner: Inner = undefined) { ,但随后出现错误:

Type 'undefined' is not assignable to type 'Inner'. “未定义”类型不能分配给“内部”类型。 'Inner' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.ts(2322)` 'Inner' 可以用与 'undefined'.ts(2322) 无关的任意类型实例化

Adding = undefined to the generic type fixed the issue:= 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>

Thanks to Nadia Chibrikova for suggesting in comments :感谢Nadia Chibrikova评论中提出建议:

Try class Example<Inner = undefined> { inner?: Inner;试试 class Example<Inner = undefined> { inner?: Inner; ...? ...?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM