I want to constrain my generic Foo class to accept only certain types.
Also, I need to auto-derive the type by the default value that is passed to the constructor of Foo.
With just Foo<T>
, when I call new Foo("bar")
the type is Foo<string>
. That is what I want.
However, when I try to restrict type T
as seen below, when I call new Foo("bar")
the type is Foo<"bar">
. Is there a way to make the compiler to still derive string
?
type FieldTypes = string | number | boolean | Date | null;
class Foo<T extends FieldTypes> {
private value: T;
constructor(defaultValue: T) {
this.value = defaultValue;
}
}
const foo: Foo<"bar"> = new Foo("bar"); // this should be of type Foo<string>