typescript

Typescript check for the 'any' type


Is it possible to check for the exact any type using typescript conditionals?

type IsAny<T> = T extends any ? true : never

type A = IsAny<any> // true
type B = IsAny<number> // never
type C = IsAny<unknown> // never
type D = IsAny<never> // never

Solution

  • Yeah, you can test for any:

    type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N; 
    type IsAny<T> = IfAny<T, true, never>;
    type A = IsAny<any> // true
    type B = IsAny<number> // never
    type C = IsAny<unknown> // never
    type D = IsAny<never> // never
    

    The explanation for this is in this answer. In short, any is intentionally unsound, and violates the normal rules of types. You can detect this violation because it lets you do something crazy like assign 0 to 1.