当数组为空时,TS 不进行类型检查。
我的代码如下:
我的代码如下:
type List = { name: string }[]
const l: List = []
// error
l[0].name
有没有办法让 TypeScript 进行检查?我该如何使用 TypeScript 进行检查?
type List = { name: string }[]
const l: List = []
// error
l[0].name
有没有办法让 TypeScript 进行检查?我该如何使用 TypeScript 进行检查?
在您的tsconfig.json
文件中,在compilerOptions
中启用noUncheckedIndexedAccess
。
这样做后,您将开始收到类似于Object is possibly 'undefined'.(2532)
的TS错误提示,针对此类语句。
type List = { name: string }[]
const l: List = []
l[0].name // <-- error
l[0]?.name // <-- no error (ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
请注意,noUncheckedIndexedAccess
选项不会检查您的数组长度;它只是一直提醒您正在尝试访问的索引可能不存在。
如果您的数组(及其元素)仅用于读取,您还可以使用const断言:
const l = [{ name: 'foo' }] as const
l[0].name // no error
l[1] // error: Tuple type 'readonly [{ readonly name: "foo"; }]' of length '1' has no element at index '1'.(2493)
// based on - https://dev59.com/sVQK5IYBdhLWcg3wF8B6#52490977
type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N ? Readonly<R> : _TupleOf<T, N, [T, ...R]>
type Tuple<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never
type List = Tuple<{ name: string }, 1>
const l: List = [{ name: 'foo' }]
l[0].name // no error
l[1] // error: Tuple type 'readonly [{ name: string; }]' of length '1' has no element at index '1'.(2493)
const l: List = getSomeListUsingUser(input);
- 那么TS就无法知道列表包含多少项。同样,它也不知道任何特定位置是否为空,例如[a, b, , d]
将具有length = 4
,但是l [2]
不存在。 - VLAZ