In my current project, I have a class with a single generic parameter T
. The challenge arises when this class is sometimes constructed with a known value for T
, and other times without a value, leaving T
in an unknown state. It becomes cumbersome to always specify the type explicitly, especially when inference could potentially handle it.
This issue can be simplified to a specific problem I'm encountering with another class that requires T
to be defined rather than remain unknown, even if no initial value is provided as it may be assigned later on.
class Foo<T> {
value: T;
constructor(value?: T) {
if (value != null && value != undefined) {
this.value = value;
}
}
public set(value: T) {
this.value = value;
}
}
const fn1 = (): Foo<number> => {
const foo = new Foo(0); //foo is Foo<number>
foo.set(1);
return foo; //No error
}
const fn2 = (): Foo<number> => {
const foo = new Foo(); //foo is Foo<unknown>
foo.set(1);
// Although 'unknown' accepts 'number' values,
// I aim to re-evaluate foo as Foo<number>.
return foo; //Error
}
const fn3 = (): Foo<number> => new Foo(); //No error, inferred as Foo<number>
I find myself wondering if there's a way to update the generic type from unknown to a specific type in such scenarios?
Alternatively, is there a mechanism to prevent the type from ever becoming unknown? Perhaps enforcing the specification of a type when calling new Foo()
? Additionally, while using Foo<any>
offers some flexibility, is there a technique to make any
the default type?
I acknowledge that one simple solution would involve explicitly stating new Foo<number>()
, but ideally, TypeScript should be able to deduce types without manual intervention, thus minimizing unnecessary efforts.