Closed
Description
#13487 added default generic types, but it's still not possible to provide a default implementation for a method, which returns the default generic type:
class A {
foo: any;
}
class B extends A {
bar: any;
}
class C<T = A> {
// this is the default implementation of the `create` method
public create(): T {
// Until now the error `Type 'A' is not assignable to type T` is thrown
// To surpress this error you have to make an unsafe upcast to `T`
// e.g. `return new A() as T;`
return new A();
}
}
class D extends C<B> {
// An error should be thrown and the user should be forced to overwrite the default implementation,
// because he provided another Type than the default type `A`
}
class E extends C<A> {
// The default type `A` was specified,
// so the default implementation of the method is fine
}
class F extends C {
// No type was specified and the default type is used,
// so the default implementation of the method is fine
}
Here the class C
, which has the default type A
for its generic type T
, provides a default implementation for the method create
. If this method is not overwritten it returns an instance of the default type A
. Now there are two possible options of extending the class C
:
- Another type than the default type
A
was specified: An error should be thrown, that the type of the returned value of thecreate
method is not assignable to the specified type and the method should be overwritten to return a value of the correct type. - The same type as the default type
A
or no type was specified: The default implementation of thecreate
method works fine and no error should be thrown.
With this approach unsafe upcast to the generic type T
of the return value of the default create
method would be prevented.