TypeScript
Beginner
1 min read
Awaited, Template Literal Utilities, and Custom Utilities
Example
// Awaited — unwrap nested promises
type P1 = Awaited<Promise<string>>; // string
type P2 = Awaited<Promise<Promise<number>>>; // number
type P3 = Awaited<string | Promise<boolean>>; // string | boolean
async function fetchData(): Promise<{ id: number; name: string }> {
return { id: 1, name: "Alice" };
}
type FetchedData = Awaited<ReturnType<typeof fetchData>>;
// { id: number; name: string }
// String manipulation utility types
type EventName = "click" | "focus" | "mouseenter";
type UpperEvents = Uppercase<EventName>; // "CLICK" | "FOCUS" | "MOUSEENTER"
type Handlers = `on${Capitalize<EventName>}`; // "onClick" | "onFocus" | "onMouseenter"
// Custom utility: Prettify — flatten intersection types for readability
type Prettify<T> = { [K in keyof T]: T[K] } & {};
type A = { name: string } & { age: number } & { id: number };
type PrettyA = Prettify<A>; // { name: string; age: number; id: number }
// Custom utility: Optional — make specific keys optional
type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
interface StrictUser { id: number; name: string; bio: string; avatar: string }
type FlexibleUser = Optional<StrictUser, "bio" | "avatar">;
// { id: number; name: string; bio?: string; avatar?: string }
// Custom utility: ReadonlyDeep
type ReadonlyDeep<T> = {
readonly [K in keyof T]: T[K] extends object ? ReadonlyDeep<T[K]> : T[K];
};
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript