Home     /Articles     /

The Hidden TypeScript Hack You Need to Know

Typescript

The Hidden TypeScript Hack You Need to Know

Written by Briann     |

November 30, 2024     |

1.4k |

Hey there TypeScript enthusiasts.


I will not waste your time with a long introduction today, let’s get straight to it!


1. The Trick

If you have been using TypeScript for some time now, you will have likely come across union types.


Union types take this form:

type Fruit = "apple" | "orange"


Now if you annotate a variable with the Fruit type, you will only be able to assign it either apple or orange.

type Fruit = "apple" | "orange" // Can only be "apple" or "orange"
const fruit: Fruit = "apple"


This is cool, but there are other fruits out there like bananas, berries, and tomatoes.


And please don’t debate this in the comments, a tomato is a fruit not a vegetable.


Related Articles