Back to notes
#TypeScript#Programming#Tips

Advanced TypeScript Patterns

Mastering TypeScript with advanced utility types, conditional types, and inference. Elevate your type safety.

Advanced TypeScript Patterns

TypeScript's type system is incredibly powerful. Beyond basic interfaces, it offers tools to make your code robust and self-documenting.

1. Conditional Types

Conditional types allow you to create types that change based on other types.
type IsString<T> = T extends string ? true : false; type A = IsString<string>; // true type B = IsString<number>; // false

Distributive Conditional Types

When used with unions, conditional types distribute over the union members:
type ToArray<T> = T extends any ? T[] : never; type StrOrNumArr = ToArray<string | number>; // Result: string[] | number[]

2. The
infer
Keyword

infer
allows you to extract types from within other types.

Extracting Return Type

type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never; function getUser() { return { id: 1, name: "Alice" }; } type User = MyReturnType<typeof getUser>; // Result: { id: number; name: string; }

3. Template Literal Types

You can build complex string types using template literals.
type Event = "click" | "hover"; type Element = "button" | "input"; type EventHandler = `on${Capitalize<Event>}${Capitalize<Element>}`; // Result: "onClickButton" | "onClickInput" | "onHoverButton" | "onHoverInput"
[!NOTE] Template literal types are extremely useful for typing API routes or CSS classes.

4. Utility Types for Props

When building React components, use these utilities to keep props clean.

ComponentProps

Extract props from an existing component:
import { ComponentProps } from "react"; function CustomButton(props: ComponentProps<"button">) { return <button {...props} className="custom-class" />; }

Recursive Types

TypeScript can even handle recursive structures (up to a limit).
type Json = | string | number | boolean | null | { [property: string]: Json } | Json[]; const data: Json = { items: [ { id: 1, value: "test" } ] };
Mastering these patterns will significantly improve your code's type safety and developer experience.