Typesafe way to render conditionally based on whether array has zero, one or many elements?

Given an array with one or more elements, the idea is to display different UIs. With React, this can be done in a typesafe way by returning different JSX after an
if
check,

if (array.length === 0) {
  // return emtpy sate
}

if (array[0] && array.length === 1) {
  const item = array[0] // this has a non-null type
  // return jsx
}

return array.map(...)


How can the same be achieved with Solid? Seems that
<Switch /> / <Match />
was a good place to start, although the
where
's boolean check doesn't perform type narrowing, so the typecheck fails: the array could be empty and accessing the first element could return
undefined
.

When adding
<Show />
to the mix, the type safety can be improved,

<Switch>
  <Match when={array.length === 0}>...</Match>
  <Match when={array.length === 1}>
    <Show when={array[0]}>
      {(item) => (<>
        {/* Here `item` is typed */}
        <p>{item().foo}</p>
      </>)}
    </Show>
  </Match>
  <Match when={array.length > 1}>...</Match>
</Switch>


although this seems overly verbose, and I feel uneasy about using
<Show>
just for its non-null assertion. Are there better options?
Was this page helpful?