typescript - 当字符串与对象的键不匹配时强制类型错误
问题描述
在 TypeScript 4.4.3 中,如何导致'c'
下面的错误字符串显示类型错误(因为它不是doSomething
方法的第一个参数的对象的键之一)?
const doSomething = ({ a, b }: { a: number, b: string }): boolean => {
return a === 1 || b === 'secret'
}
type SomethingParameterName = keyof Parameters<typeof doSomething>[0]
const orderedParameterNames = [
'b', 'c', 'a' // why no type error for 'c'?
] as SomethingParameterName[]
请在 TypeScript Playground中查看此代码。
我玩const
了一下,直接尝试了,'c' as SomethingParameterName
但这也没有给出类型错误。在这种情况下,我没有一种简单的方法可以从函数本身之外的其他来源获取键列表。
解决方案
TypeScript 构造as TypeName
本质上是一种类型转换。因为 const 字符串联合的基类型是string
,所以 TypeScript 接受这种类型转换作为兼容的类型断言。要获得预期的错误,请定义变量的类型orderedParameterNames
,而不是强制转换分配给它的值:
const orderedParameterNames: SomethingParameterName[] = [
'b', 'c', 'a'
]
现在这将给出一个错误'c'
:
TS2322:类型 '"c"' 不可分配给类型 '"a" | “乙”。
推荐阅读
- javascript - 将数据从一个数组重新排列到另一个数组的不同方法
- tortoisesvn - 如何从命令提示符打开 Tortoise SVN 提交 UI
- python - 为什么从 CSV 文件导入数据时出现此 DBeaver 错误?
- python - 模板列表的第一个元素/Django
- python - 如何为两个列表框使用单个滚动滑块
- algorithm - 如何在处理中使用 Bresenham 的线算法在网格中创建一条线
- python - ValueError:密集层的输入 0 不兼容
- flutter - 另一个 PageView 内的 PageView 的颤振块滚动
- python - 无法使用 python27 将 pyinstaller 3.5 版安装到 wine 上
- android - Dagger 2 - 为什么我收到循环引用错误?