It is intriguing how TypeScript allows the instantiation of a generic class without specifying the actual generic type parameter.
For instance, in the code snippet below, the class Foo
includes a generic type parameter T
.
However, when creating a new Foo
instance with const foo = new Foo()
, there is no requirement to specify the generic type parameter.
Thus, foo
is of type Foo<unknown>
and bar
is of type valueType<unknown>
.
Why does TypeScript allow this behavior without throwing an error? What practical application does it serve? Is there a way to enforce TypeScript to mandate the inclusion of a generic type parameter?
type valueType<T> = {
name: string,
key: T|null,
};
class Foo<T> {
private value: valueType<T>;
public constructor() {
this.value = {
name: '',
key: null,
};
}
public setValue(value: valueType<T>) {
this.value = value;
}
public getValue(): valueType<T> {
return this.value;
}
}
const foo = new Foo();
const bar = foo.getValue();