typescript - 打字稿:为什么 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
解决方案
来自关于类型断言的文档:
类型断言与强制转换
它不被称为“类型转换”的原因是转换通常意味着某种运行时支持。但是,类型断言纯粹是一种编译时构造,是一种向编译器提供关于如何分析代码的提示的方法。
这意味着,foo as string
将导致 TypeScript 编译器将 foo
其视为字符串,即使它不是字符串。具体来说,undefined
不会undefined
被 TS 编译器认为它是一个字符串神奇地变成 not-。
然而,TypeScript 也知道很少有不是字符串的东西可以被明智地视为字符串,所以你会得到一个错误(除非你欺骗它忘记它最初是什么)。
推荐阅读
- python - Python - 将一张图片粘贴到另一张图片上
- python - 从另一个子文件夹导入一个类
- linux - /usr/bin/ld: 找不到 -lpq 问题
- ios - SwiftUI ScrollView 使用 .id() 滚动过去的元素
- c# - 如何在 F# 中使用 Xamarin.Forms.Maps 创建自定义事件?
- mobx - 在 mobx 模型中我应该为 RouterStore 设置哪种类型?
- vb.net - 如何声明全局变量并在函数中使用它们 [Visual Basic]
- python - Pandas 如果列包含字符串,则从另一列获取唯一值并从数据框中删除行
- python - psycopg2 不能用 docker 安装
- python - 在 Numpy 中对每次操作的浮点精度进行基准测试