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

Viewed 212

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)`

1 Answers

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; ...?

Related