首页 > 解决方案 > 打字稿:为什么 undefined as unknown as string 会导致 undefined?

问题描述

我的印象是对字符串的类型断言会导致以前未知的类型变成字符串。我很欣赏一些关于为什么不是这种情况的解释。

$npx ts-node
> undefined as string
[eval].ts:1:1 - error TS2352: Conversion of type 'undefined' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
> undefined as unknown as string
undefined

标签: typescript

解决方案


来自关于类型断言的文档

类型断言与强制转换

它不被称为“类型转换”的原因是转换通常意味着某种运行时支持。但是,类型断言纯粹是一种编译时构造,是一种向编译器提供关于如何分析代码的提示的方法。

这意味着,foo as string将导致 TypeScript 编译器 foo其视为字符串,即使它不是字符串。具体来说,undefined不会undefined被 TS 编译器认为它是一个字符串神奇地变成 not-。

然而,TypeScript 也知道很少有不是字符串的东西可以被明智地视为字符串,所以你会得到一个错误(除非你欺骗它忘记它最初是什么)。


推荐阅读