How can I prevent a generic type from taking "any" as its type argument? [duplicate]
Asked Answered
S

1

7

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?

Stoops answered 19/4, 2021 at 16:1 Comment(4)
Also strongly related to How to undestand relations between types any, unknown, {} and between them and other types?, as the properties you ascribe to any are actually correct of unknown (that is, everything extends unknown, but unknown only extends unknown itself).Effete
If you do not think your question is addressed by either of the two above-linked question/answers, please edit it to highlight the differences and the remaining issues. Otherwise I am inclined to mark this as a duplicate pointing to them. Good luck!Effete
@Effete Yes. The question from your second comment in particular makes it extremely clear that it is by design that this occurs. Thank you!Stoops
Try type MyType<T extends OneOrTwo> = 0 extends 1 & T ? never : T; this will prevent any to be set as typeDonnell
T
1

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

Tabriz answered 19/4, 2021 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.