Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Union and Intersection Types | Working with Complex and Composed Types
Practice
Projects
Quizzes & Challenges
Quiz
Challenges
/
TypeScript Types Fundamentals

bookUnion and Intersection Types

Scorri per mostrare il menu

Union and intersection types in TypeScript allow you to write more flexible and expressive type definitions. A union type uses the pipe symbol (|) to indicate that a value can be one of several types.

An intersection type uses the ampersand (&) to combine multiple types into one. The resulting type must satisfy all the properties of each type involved.

1234567891011121314151617181920
// Union type: a value can be a string OR a number let userId: string | number; userId = "abc123"; console.log("User ID (string):", userId); userId = 42; console.log("User ID (number):", userId); // Intersection type: a value must have properties of both types type Name = { name: string }; type Age = { age: number }; type Person = Name & Age; const person: Person = { name: "Alice", age: 30, }; console.log("Person (intersection type):", person);
copy

In the code above, userId can be either a string or a number, so you can assign both "abc123" and 42 to it. This is helpful when a variable might accept more than one type, such as an ID that could be stored as a string or a number.

In the code sample, the Person type is an intersection of the Name and Age types, so an object of type Person must have both a name property of type string and an age property of type number. This is useful when you want to combine several type definitions into a single, more specific one.

Choosing between union and intersection types depends on your needs: use a union when a value can be one of several types, and use an intersection when a value must satisfy all the types at once.

question mark

Which scenario is best for using a union type instead of an intersection type?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 3

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 2. Capitolo 3
some-alt