在下面的代码中,TS将y
的类型推断为string
,而它是undefined
.有没有可能在不为y
显式定义string|undefined
类型的情况下修复它?
const x: string[] = []
const y = x[0]
在下面的代码中,TS将y
的类型推断为string
,而它是undefined
.有没有可能在不为y
显式定义string|undefined
类型的情况下修复它?
const x: string[] = []
const y = x[0]
在tsconfig.json中设置"noUncheckedIndexedAccess": true
:
"打开noUncheckedIndexedAccess将向类型中任何未声明的字段添加undefined
":https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess
// with noUncheckedIndexedAccess=true
const x: string[] = [];
const y = x[0];
y; // const y: string | undefined