简体   繁体   中英

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":

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:

Type 'undefined' is not assignable to type 'Inner'. 'Inner' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.ts(2322)`

Adding = undefined to the generic type fixed the issue:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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