Looking to implement an optional parameter within a constructor, where the type is automatically determined based on the property's type. However, when no argument is provided, TypeScript defaults to the type "unknown" rather than inferring it as "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 workaround for this without explicitly specifying the generic type or the argument?
I attempted using a default value like this:
constructor(inner: Inner = undefined) {
, but encountered 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)