Member-only story

7 Secret TypeScript Tricks Pros Use 😎🤫

Tapajyoti Bose
4 min readMay 14, 2023

--

TypeScript is an outstanding tool to make our lives easier & avoiding bugs, yet sometimes feels overwhelming to use.

This article outlines 7 TypeScript tricks that will make your life easier which all pros use.

1. Type Inference

Typescript is smart enough to infer the data types when you help it narrow them down.

enum CounterActionType {
Increment = "INCREMENT",
IncrementBy = "INCREMENT_BY",
}

interface IncrementAction {
type: CounterActionType.Increment;
}

interface IncrementByAction {
type: CounterActionType.IncrementBy;
payload: number;
}

type CounterAction =
| IncrementAction
| IncrementByAction;

function reducer(state: number, action: CounterAction) {
switch (action.type) {
case CounterActionType.Increment:
// TS infers that the action is IncrementAction
// & has no payload
return state + 1;
case CounterActionType.IncrementBy:
// TS infers that the action is IncrementByAction
// & has a number as a payload
return state + action.payload;
default:
return state;
}
}

As shown above, TypeScript infers the type of the action based on the type property, so you DON'T need to check whether payload exists.

2. Literal Types

Often you need specific values for a variable, that’s where literal types come in handy.

type Status = "idle" | "loading" | "success" | "error";

It works for numbers too:

type Review = 1 | 2 | 3 | 4 | 5;

// or better yet:
const reviewMap = {
terrible: 1,
average: 2,
good: 3,
great: 4,
incredible: 5,
} as const;

// This will generate the same type as above,
// but it's much more maintainable
type Review = typeof reviewMap[keyof typeof reviewMap];

3. Type Guards

Type guards are another method to narrow down the type of a variable:

function isNumber(value: any): value is number {
return typeof value === "number";
}

const validateAge = (age: any) => {
if…

--

--

Tapajyoti Bose
Tapajyoti Bose

Written by Tapajyoti Bose

Top Rated Freelancer || Blogger || Cross-Platform App Developer || Web Developer || Open Source Contributor || FIRE Enthusiast

Responses (4)

Write a response