Search code examples
solid-js

SolidJS: Typescript error says value is of type 'undefined' despite checking that it isn't


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?


Solution

  • 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>