Photo by Jake Hills on Unsplash

Advanced TypeScript Techniques for Senior React Developers

Asim Zaidi
6 min readMar 11

As a Senior React Developer, you’re always looking for ways to improve your skills and write better code. One technology that can help you achieve this is TypeScript. TypeScript is a statically typed language that is a superset of JavaScript. It provides developers with advanced features such as type checking, interfaces, and generics, which can help catch errors early on and improve the overall quality of your code.

In this article, we’ll explore some advanced TypeScript techniques that Senior React Developers can use to take their skills to the next level. We’ll cover topics such as Type Guards, Discriminated Unions, Conditional Types, and more.

Type Guards

Type Guards are a way to narrow down the type of a variable or expression within a block of code. They are useful when dealing with complex data structures, where it’s not always clear what the type of a variable is.

For example, let’s say you have an interface for a person that looks like this:

interface Person {
name: string;
age: number;
address?: {
street: string;
city: string;
state: string;
}
}

You have a function that takes a person as an argument and needs to check if the person has an address. You can use a Type Guard to narrow down the type of the person and check if it has an address:

function hasAddress(person: Person): person is Person & { address: object } {
return person.address !== undefined;
}

function getAddress(person: Person): string {
if (hasAddress(person)) {
return `${person.address.street}, ${person.address.city}, ${person.address.state}`;
}
throw new Error("Person does not have an address.");
}

In this example, we define a Type Guard called hasAddress that checks if the person argument has an address property. If it does, the Type Guard returns true, and the type of person is narrowed down to Person & { address: object }. This means that person has an address property.

We then use the Type Guard in the getAddress function to check if person has an address. If it does, we return the address as a string. If it doesn't, we throw an error.

Discriminated Unions

Asim Zaidi

Building AI Hub @Apple | Prev: SSWE @Atlassian | Co-Founder @jail.app | Shipping products users love | Helping people break into tech @ techmade.co