當陣列為空時,TS不做型別檢查
我的代碼在這里
type List = { name: string }[]
const l: List = []
// error
l[0].name
有什么辦法可以做TS檢查嗎?如何做TS檢查?
uj5u.com熱心網友回復:
允許noUncheckedIndexedAccess在compilerOptions你的tsconfig.json。
在此之后,您將開始收到類似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 [{ 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370695.html
標籤:打字稿
