首页 > 解决方案 > 当字符串与对象的键不匹配时强制类型错误

问题描述

在 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

解决方案


TypeScript 构造as TypeName本质上是一种类型转换。因为 const 字符串联合的基类型是string,所以 TypeScript 接受这种类型转换作为兼容的类型断言。要获得预期的错误,请定义变量的类型orderedParameterNames,而不是强制转换分配给它的值:

const orderedParameterNames: SomethingParameterName[] = [
  'b', 'c', 'a'
]

现在这将给出一个错误'c'

TS2322:类型 '"c"' 不可分配给类型 '"a" | “乙”。


推荐阅读