#typescript #types #advanced

Day 22: Conditional Types

If-Else for Types

Welcome to Day 22! We’re getting into the advanced magic. Conditional types allow us to ask questions about types.

Syntax

It looks exactly like a ternary operator in JavaScript.

SomeType extends OtherType ? TrueType : FalseType

Example: Extracting Id Types

Imagine we want a type that extracts the id type from an object if it exists, or returns never.

type GetIdType<T> = T extends { id: infer ID } ? ID : never;

interface User { id: number; name: string; }
interface Post { id: string; title: string; }
interface Settings { theme: string; }

type UserId = GetIdType<User>; // number
type PostId = GetIdType<Post>; // string
type SettingsId = GetIdType<Settings>; // never

The infer Keyword

Notice infer ID above? It tells TypeScript: β€œIf this condition is true, figure out what type is at this spot and assign it to variable ID so I can return it.”

This is how utility types like ReturnType and Parameters are built!

type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

function demo() { return "hello"; }
type DemoReturn = MyReturnType<typeof demo>; // string

Challenge for Today

  1. Create a type Flatten<T>.
  2. If T is an array (U[]), return type U.
  3. Otherwise, return T itself.
  4. Test with string[] (should be string) and number (should be number).

See you on Day 23 for Template Literal Types!