How can I prevent a generic type from taking "any" as its type argument?

Viewed 492

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?

1 Answers

At the time of writing you cannot. Writing any anywhere in the code means TypeScript going to do NO checks at all, and this propagates. You can prevent implicit any in some cases, by setting a combination of the following:

  • strict
  • noImplicitAny
  • stricNullCecks
  • noStrictGenericChecks
  • strictFunctionTypes
  • strictBindCallApply

inside tsconfig.json

Related