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
.