bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/TypeScript/TypeScript Core
TypeScript•TypeScript Core

TypeScript Advanced Types

Concept visual

TypeScript Advanced Types

visit parent, then branch83161014

Advanced TypeScript Types

TypeScript's advanced type system allows you to model complex type relationships with precision. These features are particularly useful for building robust, maintainable applications with excellent type safety.

Key Advanced Type Features

Mapped Types

: Transform properties of existing types

Conditional Types

: Create types based on conditions

Template Literal Types

: Build types using string templates

Utility Types

Formula

: Built - in type helpers for common transformations

Recursive Types

Formula

: Self - referential types for tree - like structures

Type Guards & Type Predicates : Runtime type checking

Type Inference

: Advanced pattern matching with infer

Mapped Types

Mapped types allow you to create new types by transforming properties of existing types.

Basic Mapped Type

Transform every property of an object type into a new type using a single template.

Example

// Convert all properties to boolean type Flags<T> = {
[K in keyof T]: boolean;
};
interface User {
id: number;
name: string;
email: string;
}
type UserFlags = Flags<User>;

// Equivalent to:

// {
//   id: boolean;
//   name: boolean;
//   email: boolean;
// }

Mapped Type Modifiers

Add or remove property modifiers like readonly and ? across all keys.

Example

// Make all properties optional interface Todo {
title: string;
description: string;
completed: boolean;
}
type OptionalTodo = {
[K in keyof Todo]?: Todo[K];
};
// Remove 'readonly' and '?' modifiers type Concrete<T> = {
-readonly [K in keyof T]-?: T[K];
};
// Add 'readonly' and 'required' to all properties type ReadonlyRequired<T> = {
+readonly [K in keyof T]-?: T[K];
};

Key Remapping

Rename or filter keys while mapping using as, string helpers, and conditional checks.

Example

// Add prefix to all property names type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
// {
//   getId: () => number;
//   getName: () => string;
//   getEmail: () => string;
// }
// Filter out properties type MethodsOnly<T> = {
[K in keyof T as T[K] extends Function ? K : never]: T[K];
};

Conditional Types

Conditional types allow you to define types that depend on a condition.

Basic Conditional Types

Select between types based on a condition checked at the type level.

Example type IsString<T> = T extends string ? true : false;

type A = IsString<string>;    // true type B = IsString<number>;    // false type C = IsString<'hello'>;    // true type D = IsString<string | number>; // boolean

Formula

// Extract array element type type ArrayElement < T > = T extends (infer U)[] ? U : never;
type Numbers = ArrayElement<number[]>; // number

Infer Keyword

Capture a part of a type within a conditional type by introducing a new type variable with infer.

Example

Formula

// Get return type of a function type ReturnType < T > = T extends (...args: any[]) => infer R ? R : any;
// Get parameter types as a tuple type Parameters < T > = T extends (...args: infer P) => any ? P : never;
// Get constructor parameter types type ConstructorParameters < T extends new (...args: any) => any > =
T extends new (...args: infer P) => any ? P : never;

Formula

// Get instance type from a constructor type InstanceType < T extends new (...args: any) => any > =
T extends new (...args: any) => infer R ? R : any;

Distributed Conditional Types

Understand how conditionals distribute over unions versus when they are wrapped to prevent distribution.

Example

Formula

// Without distribution type ToArrayNonDist < T > = T extends any ? T[] : never;
type StrOrNumArr = ToArrayNonDist<string | number>; // (string | number)[]

Formula

// With distribution type ToArray < T > = [T] extends [any] ? T[] : never;
type StrOrNumArr2 = ToArray<string | number>; // string[] | number[]

Formula

// Filter out non - string types type FilterStrings < T > = T extends string ? T : never;
type Letters = FilterStrings<'a' | 'b' | 1 | 2 | 'c'>; // 'a' | 'b' | 'c'

Template Literal Types

Template literal types allow you to build types using template literal syntax.

Basic Template Literal Types

Constrain strings to specific patterns using template literals and unions.

Example type Greeting = `Hello, ${string}`;
const validGreeting: Greeting = 'Hello, World!';
const invalidGreeting: Greeting = 'Hi there!'; // Error
// With unions type Color = 'red' | 'green' | 'blue';
type Size = 'small' | 'medium' | 'large';
type Style = `${Color}-${Size}`;

Formula

// 'red - small' | 'red - medium' | 'red - large' |
// 'green - small' | 'green - medium' | 'green - large' |
// 'blue - small' | 'blue - medium' | 'blue - large'

String Manipulation Types

Formula

Apply built - in helpers to transform string literal types (uppercasing, capitalizing, etc.).

Previous

TypeScript Tooling

Next

TypeScript Type Guards