nearworld
nearworld

Reputation: 45

narrowing the type of array elements is working with variable but not index

type Soccer = { ball: string }
type Basketball = { jump: string }
type Data = Soccer[] | Basketball[]

if ('ball' in data[index]) { // type guard does not work here.
  <MyComponent something={data[index]} /> // data: Soccer[] | Basketball[]
}
const resultObj = data[index] // indexed element is assigned to variable.

if ('ball' in resultObj)
  <MyComponent resultObj={resultObj} /> // works with variable
if (data)
  <MyComponent resultObj={data[index]} /> // not works with index.

I don't understand how assigning data[index] to variable solved the type narrowing issue. I expected 'ball' in data[index] would work. But it did not..

Upvotes: 1

Views: 63

Answers (1)

Phillip
Phillip

Reputation: 6253

Type narrowing does not work if the index is not a literal (I reckon that index in your example is of type number).

Your best workaround is what you're already doing: assign the value of data[index] to a variable and narrow that down.


See more here: https://github.com/microsoft/TypeScript/issues/10530

Upvotes: 2

Related Questions