0
0
Typescriptprogramming~5 mins

Extract type in Typescript

Choose your learning style9 modes available
Introduction

The Extract type helps you pick only certain parts from a group of options. It makes your code cleaner by choosing just what you need.

When you want to select specific words from a list of strings.
When you need to filter types to only those that match a certain pattern.
When you want to reuse parts of a type but not all of it.
When you want to make sure a variable only holds certain allowed values.
Syntax
Typescript
Extract<Type, Union>

Type is the original set of types you want to filter.

Union is the set of types you want to keep from Type.

Examples
This picks only the vowels from the letters. Since only 'a' is in Letters, the result is 'a'.
Typescript
type Letters = 'a' | 'b' | 'c' | 'd';
type Vowels = Extract<Letters, 'a' | 'e' | 'i' | 'o' | 'u'>;  // 'a'
This extracts only even numbers from the Numbers type.
Typescript
type Numbers = 1 | 2 | 3 | 4 | 5;
type EvenNumbers = Extract<Numbers, 2 | 4 | 6 | 8>;
// Result: 2 | 4
This keeps only string and boolean types from the Mixed type.
Typescript
type Mixed = string | number | boolean;
type StringsOnly = Extract<Mixed, string | boolean>;
// Result: string | boolean
Sample Program

This program defines a type Pets with some animals. Then it extracts only common pets (cat and dog) from it. It shows how you can use Extract to limit allowed values.

Typescript
type Pets = 'dog' | 'cat' | 'parrot' | 'fish';
type CommonPets = Extract<Pets, 'cat' | 'dog' | 'hamster'>;

const myPet1: CommonPets = 'dog';
const myPet2: CommonPets = 'cat';
// const myPet3: CommonPets = 'parrot'; // Error: 'parrot' not in CommonPets

console.log(myPet1);
console.log(myPet2);
OutputSuccess
Important Notes

Extract only keeps types that exist in both sets.

If no types match, the result is never.

It is useful to narrow down union types safely.

Summary

Extract picks matching types from a bigger set.

Use it to filter union types easily.

It helps keep your code clear and safe.