在您的tsconfig.json 中启用noUncheckedIndexedAccess in compilerOptions。
在此之后,您将开始在此类语句中收到诸如 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://stackoverflow.com/a/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)