The utility types in TypeScript
The built-ins worth memorising, and what each one is for.
interface Run {
lang: string;
tpm: number;
stars: number;
note?: string;
}
type Summary = Pick<Run, "lang" | "tpm">;
type WithoutNote = Omit<Run, "note">;
type ByLang = Record<string, Summary>;
type Patch = Partial<Run>;
type Complete = Required<Run>;
async function load(): Promise<Run[]> {
return [];
}
type Loaded = Awaited<ReturnType<typeof load>>;
type Args = Parameters<(lang: string, tpm: number) => void>;
const summary: Summary = { lang: "ts", tpm: 98 };
const table: ByLang = { ts: summary };
const patch: Patch = { stars: 3 };
const rows: Loaded = [];
const args: Args = ["ts", 98];
console.log(table.ts?.tpm, patch.stars, rows.length, args[0]);
How it works
PickandOmitselect or drop keys.Recordbuilds a map type;Awaitedunwraps a promise.ReturnTypeandParametersread a function's type.
Keywords and builtins used here
ArgsByLangLoadedPatchPromiseSummaryasyncconstfunctioninterfacenumberreturnstringsummarytype
The run, in numbers
- Lines
- 26
- Characters to type
- 660
- Tokens
- 196
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 118 seconds.
Step 4 of 4 in Reading types, step 8 of 20 in Generics.