G
G
Gary_Ihar2021-09-14 17:21:48
typescript
Gary_Ihar, 2021-09-14 17:21:48

How to handle such an exception using TS?

type Item = {
  title: string
}
const arr : Item[] = []
const a = arr[0].title.length //error , но TS молчит

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2021-09-14
@Gary_Ihar

const arr1 : [Item, ...Item[]] = [{ title: 'a' }] // OK
const arr2 : [Item, ...Item[]] = [] // Не скомпилируется

Playground
By using this tuple type instead of a normal array, you can REQUIRE some number of elements at the beginning of the array.

D
Dmitry Belyaev, 2021-09-15
@bingo347

If TS is higher than 4.1 then add to tsconfig.json in compilerOptions:
"noUncheckedIndexedAccess": true
TS will complain about unchecked index access

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question