10LOC

#type-inference

TypeScriptadvanced

Use NoInfer to keep generic inference predictable

export const createMethodGuard = <M extends string>(allowed: M[], fallback: NoInfer<M>) => {
  const allowedSet = new Set<string>(allowed);
  return (method: string): M => (allowedSet.has(method) ? (method as M) : fallback);
};

Prevent TypeScript from widening generic arguments when you need stable inference.

TypeScriptintermediate

satisfies to validate shape while keeping literal types

type RGB = readonly [red: number, green: number, blue: number];

const palette = {
  primary: [15, 98, 254],
  danger: [220, 38, 38],

Check an object against a type without widening it to that type, so autocomplete and literal inference on the value survive the check.