TypeScript:访问对象上未定义的键时返回的类型错误?

Sim*_*n H 3 javascript types typescript

在 TypeScript 中使用带有可变键的对象时,我注意到意外的类型。

给出以下代码

type MyType = {
  [x: number] : number
}

const o : MyType = {
  0: 1,
}

const a = o[0]; // Return type correctly identified as number
const b = o[1]; // Return type should be undefined and compiler should not allow this
Run Code Online (Sandbox Code Playgroud)

我注意到,[...]当使用变量键的语法定义对象类型时,无法正确检测到对象访问的类型[x: number]

VSCode 向我显示 和a 都有b类型number。难道类型不应该是number | undefined相反的吗,因为可能会发生键未定义的情况?当登录ab控制台时,是a一段number时间bundefined

MyType当一个类型的对象传递给一个函数并且该函数访问该对象中的键然后执行如下操作时,问题会变得更加严重:

function fun(o: MyType) : number {
   return o[10000] ?? null  // can be number or null at runtime
}
Run Code Online (Sandbox Code Playgroud)

没有显示错误。但是当代码运行时,o[10000]是未定义的,因此返回值不是null有效数字。想象一下使用这个返回值来执行进一步的计算,这些计算都基于这是一个有效数字的假设。这会导致编译器应该检测到的运行时错误(如果我不明白完全错误的地方,我是 TS 的新手)

(这些示例中使用的TypeScript是由create-react-app配置的,我没有更改任何设置)

小智 7

添加"noUncheckedIndexedAccess": true到您的 tsconfig.json complierOptions 对象