#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
- Create a type
Flatten<T>. - If
Tis an array (U[]), return typeU. - Otherwise, return
Titself. - Test with
string[](should be string) andnumber(should be number).
See you on Day 23 for Template Literal Types!