首页 经验

typescript Type Assertions

时间: 2024-09-19 08:43:32

(部分内容来自网络,其真实性存疑,为了避免对您造成误导,请谨慎甄别。)


TypeScript only allows type assertions which convert to a more specific or less specific version of a type. This rule prevents “impossible” coercions like:

TypeScript 只允许转换为类型更具体或更不具体版本的类型断言。此规则可防止“不可能”的转换,例如:

const x = "hello" as number;

Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

将类型“字符串”转换为类型“数字”可能是一个错误,因为两个类型并不完全重叠。如果这是有意为之,请先将表达式转换为“未知”。


Sometimes this rule can be too conservative and will disallow more complex coercions that might be valid. If this happens, you can use two assertions, first to any (or unknown, which we’ll introduce later), then to the desired type:

有时,此规则可能过于保守,并且不允许可能有效的更复杂的强制。如果发生这种情况,您可以使用两个断言,首先是 any(或未知,我们将在后面介绍),然后是所需的类型:

const a = (expr as any) as T;

上一个 符号大全,特殊符号,各种符号 文章列表 下一个 typescript noImplicitAny

最新

工具

© 2019-至今 适观科技

沪ICP备17002269号