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

bookUnion and Intersection Types

Pyyhkäise näyttääksesi valikon

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

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 3

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 2. Luku 3
some-alt