用于安全阵列访问的 TS 配置
TS configuration for safe array access
在此代码中
const arr = ['hello', 'world'];
const x = arr[2];
const y = arr[0.5];
arr
是一个string[]
,而10
和0.5
是number
,所以TS暗示10
和0.5
可以索引 arr
,因此推断 x
和 y
也是 string
,而在运行时它们将是 undefined
.
有没有我可以在我的 tsconfig.json
中写的配置选项,它基本上告诉打字稿“如果你不确定 arr: T[]
在 i
有一个元素,不要推断arr[i]
是 T
"?
TypeScript 4.1 引入了对 checked indexed accesses 的支持,可以通过 --noUncheckedIndexedAccess
编译器选项启用。如果你打开它,你会得到这个行为:
const arr = ['hello', 'world'];
const x = arr[10] // number | undefined
console.log(x.toUpperCase()) // compiler error
// ~ <-- object is possibly undefined
console.log(x?.toUpperCase()) // okay
这就是您要查找的内容。此选项 未 包含在 the --strict
suite of type checking features 中,因为即使对于通常被认为安全的代码,它也会使编译器报错:
for (let i = 0; i < arr.length; i++) {
console.log(arr[i].toUpperCase()) // error!
// -------> ~~~~~~
// arr[i] is possibly undefined
}
所以你必须决定你想要的行为是否值得类型检查器可能发出的错误警告,如果是这样,明确地打开 --noUncheckedIndexedAccess
。
在此代码中
const arr = ['hello', 'world'];
const x = arr[2];
const y = arr[0.5];
arr
是一个string[]
,而10
和0.5
是number
,所以TS暗示10
和0.5
可以索引 arr
,因此推断 x
和 y
也是 string
,而在运行时它们将是 undefined
.
有没有我可以在我的 tsconfig.json
中写的配置选项,它基本上告诉打字稿“如果你不确定 arr: T[]
在 i
有一个元素,不要推断arr[i]
是 T
"?
TypeScript 4.1 引入了对 checked indexed accesses 的支持,可以通过 --noUncheckedIndexedAccess
编译器选项启用。如果你打开它,你会得到这个行为:
const arr = ['hello', 'world'];
const x = arr[10] // number | undefined
console.log(x.toUpperCase()) // compiler error
// ~ <-- object is possibly undefined
console.log(x?.toUpperCase()) // okay
这就是您要查找的内容。此选项 未 包含在 the --strict
suite of type checking features 中,因为即使对于通常被认为安全的代码,它也会使编译器报错:
for (let i = 0; i < arr.length; i++) {
console.log(arr[i].toUpperCase()) // error!
// -------> ~~~~~~
// arr[i] is possibly undefined
}
所以你必须决定你想要的行为是否值得类型检查器可能发出的错误警告,如果是这样,明确地打开 --noUncheckedIndexedAccess
。