typescript
/

TypeScript Union & Intersection Types

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Union & Intersection Types

What are Union Types?

Union types allow a variable to hold multiple possible types using the '|' operator.

Union Example

TypeScriptRead-only
1
let id: string | number;
id = 101;
id = 'ABC';

What are Intersection Types?

Intersection types combine multiple types into one using the '&' operator, requiring all properties.

Intersection Example

TypeScriptRead-only
1
type A = { name: string };
type B = { age: number };

type Person = A & B;

Union vs Intersection

FeatureUnion (|)Intersection (&)
MeaningEither typeBoth types
FlexibilityHighStrict
Use CaseMultiple optionsCombine structures

Practical Example

TypeScriptRead-only
1
function printId(id: string | number) {
  console.log(id);
}

Type Narrowing

TypeScriptRead-only
1
function printId(id: string | number) {
  if (typeof id === 'string') {
    console.log(id.toUpperCase());
  }
}

Best Practices

  • Use union for flexible inputs
  • Use intersection for combining types
  • Apply type narrowing for unions
  • Keep types readable

Common Mistakes

  • Confusing union with intersection
  • Not using type narrowing
  • Overcomplicating type combinations
  • Ignoring type conflicts in intersections

Conclusion

Union and intersection types provide flexibility and structure in TypeScript, enabling powerful type combinations.

Try it yourself

let id: string | number = 10;

Test Your Knowledge

Q1
of 3

Union symbol?

A
&
B
|
C
:
D
=
Q2
of 3

Intersection symbol?

A
|
B
&
C
#
D
*
Q3
of 3

Union means?

A
Both
B
Either
C
None
D
Only one

Frequently Asked Questions

What is union type?

Allows multiple possible types.

What is intersection?

Combines multiple types into one.

Symbol for union?

| symbol.

Previous

ts type alias

Next

ts enums

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.