Issue
Given the variables with types:
const someArray: number[];
const index: number | undefined;
is there a shorthand in TypeScript for the expression:
index === undefined ? undefined : someArray[index]
The above expression can become quite verbose especially if index
itself is also an expression.
I understand the expression can be wrapped into a function, I'm just curious whether there's a builtin way to write this more concisely. For example, in JS, this can be simply: someArray[index]
.
Solution
The expression
index === undefined ? undefined : someArray[index]
is not equivalent to
someArray[index]
because if index === undefined
, the former expression will definitely evaluate to undefined
, while the latter is indexing into someArray
with undefined
as the property name, which coerced undefined
to the string "undefined"
. Thus someArray[undefined]
is equivalent to someArray.undefined
. Will someArray.undefined
exist? Probably not. So in practice this is likely to be undefined
, but it is technically possible:
const myArray: number[] = Object.assign([123], { undefined: "xyz" });
const index: number | undefined = Math.random() < 0.5 ? 0 : undefined;
console.log(myArray[index] === undefined) // false
myArray[index]
in the above example cannot be undefined
.
Furthermore, even if they were equivalent, TypeScript adds a type system on top of JavaScript in order to add some type safety while still allowing for idiomatic JavaScript code. Indexing into an object or array with a key that isn't of type string
or number
or symbol
is really not idiomatic JavaScript. TypeScript takes the opinionated position that it is probably a mistake to use undefined
as an index, because it is rarely what people actually intend to do. So even if it turned out that there were no edge cases to someArray[index]
, it would still be considered illegal TypeScript. For more information, see What does "all legal JavaScript is legal TypeScript" mean?
If you really want to write someArray[index]
you can do so via type assertion and/or the any
type to loosen type checking:
someArray[index as any]
If not, then index === undefined ? undefined : someArray[index]
or a function that abstracts the operation is probably your best bet.
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.