This article's content
QuickTip: 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 To my job profile

I am Mathias from Heidelberg, Germany. I am a passionate IT freelancer with 15+ years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I create Bosycom and initiated several software projects.