3

I have some SolidJS code like:

{value() !== undefined && <img src={srcs[value()]} />}

where value is a signal. I get a TypeScript error under value() saying Type 'undefined' cannot be used as an index type.ts(2538)

What does this mean and how do I fix this without // @ts-ignore?

abc
  • 1,141
  • 12
  • 29

1 Answers1

7

Typescript has no way of knowing that value() returns the same result each time it's called. You can use non-null assertion operator for the second value()

{value() !== undefined && <img src={srcs[value()!]} />}

or you can use <Show> with callback. Show will pass the value of when, if it's showing, to the callback, and its type will be non-nullable:

<Show when={value()}>{value => <img src={srcs[value]} />}</Show>
artem
  • 46,476
  • 8
  • 74
  • 78