Typescript - Tips & Tricks - Union and Intersection

Full Stack Developer and JavaScript and TypeScript enthusiastic.
Search for a command to run...

Full Stack Developer and JavaScript and TypeScript enthusiastic.
No comments yet. Be the first to comment.
In this series, You'll see some tips and tricks using Typescript
Welcome back, guys! The topic of today is Overloaded Functions. All self-respecting programming languages have overloaded functions, so typescript has this feature too. To use this feature in typescript, we have to declare all the signatures of thi...
Today, I wanna show you how to set up your devices with Antigravity using only the agentic mode, without touching any code. At the last CodeMotion Rome, I got my special badge. A CM Node, a special ha

As a developer, you have to take control of your projects every day. Whether it is a company repository, an open source project you maintain or collaborate on, or a simple pet project. Gaining control over your projects often depends on the platform ...

My Antigravity first experience

Write clear and insightful commit messages using AI and GitLens.

We are in the AI era. New models emerge daily, and many applications have already integrated AI into their workflows. Gemini, OpenAI, Copilot, Deepseek, Llama, and many others enable AI in your applications or help you write code, but they all need a...

Hi and welcome back! Today I talk about Union and Intersection.
In some cases, we have to combine different types to create new types, or sometimes we have parameters that could be of different types. Typescript helps us with two powerful features: Union(|) and Intersection(&).
A union type describes a value that can be one of several types.
type Padding = number | string
let paddingNumber: Padding = 1
let paddingString: Padding = '----';
let paddingError: Padding = true // Type 'boolean' is not assignable to type 'Padding'.
In this case, the padding can be a number or a string, and the compiler detects if you set different types; this feature can be used also with custom types.
type Fish = {
name(): string;
swim(): true;
};
type Cat = {
name(): string;
meows(): true;
};
type Pet = Fish | Cat; // { name(): string; }
declare function createPet(): Pet;
let pet = createPet();
pet.name()
pet.swim() // Property 'swim' does not exist on type 'Pet'
pet.meows(); // Property 'meows' does not exist on type 'Pet'
In this example we can see how the union type creates the Pet type; the Pet type is composed by a single method "name". This method is the only one present in the two initial types: Fish and Cat.
An intersection type combines multiple types into one.
type Point2D = {
x: number;
y: number;
};
type Point3D = Point2D & {
z: number;
};
let point2d: Point2D = { x: 0, y: 0 };
let point3d: Point3D = { x: 0, y: 0, z: 0 };
We can see that the Point3D type is the union of the Type Point2D and the type { z: number; }.
That's all for today! See you soon guys!