#String array type `string | undefined`
17 messages · Page 1 of 1 (latest)
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] : ""```
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
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
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
its not fixed length, it comes from an api call
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
yea okay thanks!
Technically an array can have holes in it, so foo[0] is still undefined. But that's a pretty niche scenario.
json can't encode sparse arrays, so not an issue here
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])```
tbh you're better off pretending sparse arrays don't exist lol
you shouldn't be making them anyways
yeah I think that's what most people do. Just pointing it out.