10LOC

#type-narrowing

TypeScriptintermediate

Extract and Exclude in a tiny parser helper

type Assignment = { kind: "assign"; key: string; value: string };
type Flag = { kind: "flag"; key: string };
type Token = Assignment | Flag | { kind: "comment"; text: string };

const tokenize = (line: string): Token => {

Use utility conditional types to parse and narrow a small input grammar.

TypeScriptadvanced

Narrowing with in and tagged interfaces for a plugin system

interface LoggerPlugin { kind: "logger"; log(message: string): void }
interface CachePlugin { kind: "cache"; get(key: string): unknown }

export type AppPlugin = LoggerPlugin | CachePlugin;

Narrow a plugin union by checking which method it has, instead of switching on a kind tag, so adding a capability-only plugin needs no tag.

TypeScriptintermediate

Assertion functions (asserts x is T) for runtime-checked narrowing

export function assertIsString(value: unknown, name: string): asserts value is string {
  if (typeof value !== "string") {
    throw new TypeError(`${name} must be a string, got ${typeof value}`);
  }
}

Narrow a value by throwing instead of branching, so the rest of the function can assume the checked type without an extra if.