One-liners

Contents

One-liners#

Single-expression TypeScript idioms.

Type-safe Object.entries walk; the key keeps its literal type.

for (const [k, v] of Object.entries(o) as [keyof typeof o, ValueOf<typeof o>][]) { /* ... */ }

User-defined type guard.

const isString = (x: unknown): x is string => typeof x === "string";

Exhaustive never check.

function assertNever(x: never): never { throw new Error(`unhandled: ${JSON.stringify(x)}`); }

Tagged Result pattern.

type Result<T, E = Error> = {ok: true; value: T} | {ok: false; error: E};

satisfies keeps the literal type while constraining the structure.

const cfg = {host: "example.com", port: 443} satisfies {host: string; port: number};

Validate JSON with zod and infer the type.

const User = z.object({id: z.number(), name: z.string()}); type User = z.infer<typeof User>;

Discriminated narrowing.

if (s.kind === "circle") { use(s.r); } else { use(s.w, s.h); }

References#

  • Snippets for the snippets catalogue.

  • Types for the type system these guards interact with.