Back to Blog

Advanced TypeScript Types

Deep dive into TypeScript's advanced type system features.

TypeScriptDevelopment

Introduction

TypeScript's type system is incredibly powerful. Let's explore some advanced features that can help you write safer, more expressive code.

Utility Types

TypeScript provides several built-in utility types:

Partial and Required

interface User {
  id: number;
  name: string;
  email: string;
}

// All properties optional
type PartialUser = Partial<User>;

// All properties required
type RequiredUser = Required<User>;

Pick and Omit

// Only id and name
type UserPreview = Pick<User, 'id' | 'name'>;

// Everything except email
type UserWithoutEmail = Omit<User, 'email'>;

Conditional Types

Conditional types allow you to create types based on conditions:

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

type A = IsString<string>; // true
type B = IsString<number>; // false

Template Literal Types

Create string types from patterns:

type EventName = 'click' | 'focus' | 'blur';
type EventHandler = `on${Capitalize<EventName>}`;
// 'onClick' | 'onFocus' | 'onBlur'

Mapped Types

Transform existing types:

type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};

Type Guards

Create custom type guards for runtime checks:

interface Cat {
  meow(): void;
}

interface Dog {
  bark(): void;
}

function isCat(pet: Cat | Dog): pet is Cat {
  return (pet as Cat).meow !== undefined;
}

Conclusion

Mastering these advanced TypeScript features will help you write more type-safe code and catch errors at compile time rather than runtime.