Force a non-empty array in TypeScript

This is how you can force TypeScript to always have at least one item in an array. Or in other words: to not allow empty arrays.

export interface ColorSelectionProps extends HTMLAttributes<HTMLDivElement> {
  items: [ColorSelectionItem, ...ColorSelectionItem[]]
}

You can also force it to have at least 2, 3 etc. items:

export interface ColorSelectionProps extends HTMLAttributes<HTMLDivElement> {
  items: [ColorSelectionItem, ColorSelectionItem, ...ColorSelectionItem[]]
}

This came in handy lately when I was implementing a ColorSelection component in React:

export const ColorSelection: FC<ColorSelectionProps> = ({ items }) => {
  const [selected, setSelected] = useState<ColorSelectionItem>(items[0])
  // ...

Having it statically checked is way better than having a runtime check like if items.length > 0.

About Author

Mathias Bothe Contact me

I am Mathias, born 38 years ago in Heidelberg, Germany. Today I am living in Munich and Stockholm. I am a passionate IT freelancer with more than 14 years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I am founder of bosy.com, creator of the security service platform BosyProtect© and initiator of several other software projects.