当数组为空时,TypeScript 不进行类型检查。

3
当数组为空时,TS 不进行类型检查。
我的代码如下:
type List = { name: string }[]

const l: List = []

// error
l[0].name

有没有办法让 TypeScript 进行检查?我该如何使用 TypeScript 进行检查?


2
TS在运行时不知道数组中有多少个元素。是的,在这里它可能知道,但是想象一下代码是const l: List = getSomeListUsingUser(input); - 那么TS就无法知道列表包含多少项。同样,它也不知道任何特定位置是否为空,例如[a, b, , d]将具有length = 4,但是l [2]不存在。 - VLAZ
2
请考虑使用noUncheckedIndexedAccess - captain-yossarian from Ukraine
1个回答

6

在您的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)

Playground

请注意,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)

如果您只想要固定数组长度,但元素可变,则在 TS4.1 及以上版本中可以这样实现:
// 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接