How can I prevent a generic type from taking any
as its type argument? If my generic argument is constrained by using the extends
keyword, it feels weird that it can be replaced by any
.
As far as I understand it, everything extends any
, but any
should not extend anything (other than any
itself).
Here's an example:
type OneOrTwo = 1 | 2;
type MyType<T extends OneOrTwo> = T;
const t1: MyType<OneOrTwo> = 1; // OK
const t2: MyType<any> = 2; // OK
const t3: MyType<OneOrTwo> = 3; // Error: Type '3' is not assignable to type 'OneOrTwo';
const t4: MyType<any> = 4; // OK?? How can I prevent this?
Can I have typescript prevent me from typing t4
like this? Either by changing the code or by using a tsconfig
option maybe?
any
are actually correct ofunknown
(that is, everything extendsunknown
, butunknown
only extendsunknown
itself). – Effetetype MyType<T extends OneOrTwo> = 0 extends 1 & T ? never : T;
this will prevent any to be set as type – Donnell