在以下代码中,TS推断的类型 y 像 string 当它 undefined .是否可以在不明确定义的情况下修复它 string|undefined 的类型 y ?
y
string
undefined
string|undefined
const x: string[] = [] const y = x[0]
设置 "noUncheckedIndexedAccess": true 在tsconfig.json中:
"noUncheckedIndexedAccess": true
“打开 无未选中的索引访问 将添加 undefined 到类型中任何未声明的字段“: https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess
// with noUncheckedIndexedAccess=true const x: string[] = []; const y = x[0]; y; // const y: string | undefined
Link to playground