打字稿检查“任何"类型 [英] Typescript check for the 'any' type

查看:42
本文介绍了打字稿检查“任何"类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 typescript 条件检查确切的 any 类型?

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

推荐答案

是的,你可以测试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

对此的解释在这个答案中.简而言之,any 是故意不健全的,并且违反了类型的正常规则.您可以检测到这种违规行为,因为它可以让您做一些疯狂的事情,例如将 0 分配给 1.

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.

这篇关于打字稿检查“任何"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆