When working with TypeScript, you might define both a list of values and a type like this:
type Fruit = 'apple' | 'banana' | 'orange';
const fruits = ['apple', 'banana', 'orange'];
But writing the same values twice is:
❌ Not clean
❌ Hard to update
❌ Easy to make mistakes
Let’s learn a better way!
One Simple Trick: Write Once, Use Everywhere
You can define your list once, and TypeScript can turn it into a type automatically.
const fruits = ['apple', 'banana', 'orange'] as const;
type Fruit = (typeof fruits)[number];
Now:
✅ fruits is a normal array you can use in your app
✅ Fruit is a type that only allows 'apple' | 'banana' | 'orange'
Benefits
✅ Autocomplete works in your editor
✅ You only update one place
✅ Code is cleaner and safer
Final Tip
Use as const to make TypeScript treat the array as readonly, so it can safely create the union type.
Regards,
N I Rimon