This is a simple tip that I use a lot, but the incantation necessary to make it work never seems to stick in my brain. So Iām documenting it here for posterity.
const fruits = ['apple', 'pineapple', 'mango'] as const;
type FruitOption = typeof fruits[number]; // "apple" | "pineapple" | "mango"
When is this useful?
I usually find this is helpful when you are trying to build a typesafe select component where you simultaneously want the type of the output, but also want the input as a string. e.g.
type FruitSelectOption = { value: FruitOption; label: string };
const SELECT_OPTIONS: FruitSelectOption[] = [
{ value: "apple", label: "Apple" },
{ value: "pineapple", label: "Pineapple" },
{ value: "mango", label: "Mango" },
];
type FruitSelectorProps = {
onChange: (option: FruitSelectOption) => void;
value: FruitSelectOption;
};
const FruitSelector = ({ onChange, value }: FruitSelectorProps) => {
return <Select options={SELECT_OPTIONS} onChange={onChange} value={value} />;
};
A nice, happy typesafe form :)