Issue
When a generic class is instantiated with new
, its type parameters are inferred. Generic constraints seem to be ignored in this case.
type MyType = { a?: number, b?: number };
class MyClass<T extends MyType = MyType> {
constructor(t: T) {}
method(t: T) {}
}
const myClass1 = new MyClass<MyType>({ a: 1 });
myClass1.method({ b: 1 });
const myClass2 = new MyClass({ a: 1 });
// Why is this error?
// T should extend `MyType` even though type was inferred from a constructor parameter.
myClass2.method({ b: 1 });
Is this is a bug or an intension? Can the type inference be prevented for generic classes?
Solution
This is intentional. The extends
clause of a generic type (in this case T
) only specifies a constraint to the passed type.
The type { a: number }
does fulfill the constraint because b
is optional.
type T0 = { a: number } extends MyType ? true : false
// -> true
When it successfully fulfills the constraint, the type { a: number }
will become the type T
(without inheriting MyType
). Since b
is not part of { a: number }
, you get an error.
Answered By - Tobias S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.