#String array type `string | undefined`

17 messages · Page 1 of 1 (latest)

agile girder
#

I have a string array and when I attempt to get the value from it, I get type string | undefined

glad meteorBOT
#
bnason#0

Preview:```ts
const arr = ["foo", "bar", "baz"]

// For me in vscode foo is of type "string | undefined"
const foo = arr[0]

// Same here
const baz = foo.length > 0 ? foo[0] : ""```

fathom vapor
#

that would be because you have noUncheckedIndexedAccess enabled in your tsconfig

#

that's normal behavior

#

and ts doesn't narrow string/array access from length checks, it's just kinda infeasible

agile girder
#

What would be the best way to narrow that type? explicitly checking if its undefined and using a default value? Which I feel like would never be used especially if im already checking length. I could use as string i guesss

fathom vapor
#

narrow it after the access, or just non-null assert it if you're confident where it's from

#

if the array is fixed length you could also type it as a tuple

agile girder
#

its not fixed length, it comes from an api call

fathom vapor
#

with the length check you could non-null assert, this is a pretty reasonable situation to use it in

#

or just check after access like mentioned before

agile girder
#

yea okay thanks!

rough ether
#

Technically an array can have holes in it, so foo[0] is still undefined. But that's a pretty niche scenario.

fathom vapor
#

json can't encode sparse arrays, so not an issue here

glad meteorBOT
#
sandiford#0

Preview:```ts
const arr = ["foo", "bar", "baz"]

delete arr[0]

// For me in vscode foo is of type "string | undefined"
const foo = arr[0]
// ^?

// Same here
const baz = arr.length > 0 ? arr[0] : ""
// ^?

console.log(arr[0])```

fathom vapor
#

tbh you're better off pretending sparse arrays don't exist lol
you shouldn't be making them anyways

rough ether
#

yeah I think that's what most people do. Just pointing it out.