Typescript check for the 'any' type

后端 未结 1 1714
梦谈多话
梦谈多话 2020-12-17 22:40

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

type IsAny = T extends any ? true : never

type A = IsAny         


        
相关标签:
1条回答
  • 2020-12-17 23:02

    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.

    0 讨论(0)
提交回复
热议问题