Generic Defaults Fill Optional Type Arguments

Generic type defaults supply sensible second arguments — Error for results, string cursors for pages — while explicit call sites can still override them.

TypescriptData Integrity

Code

typescriptsnippet
33 lines
// Generic defaults give omitted call sites a sensible fallback, overridable when needed
type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

type Paginated<T, Cursor = string> = {
  items: T[];
  nextCursor: Cursor | null;
};

// Override the error type explicitly: parse failures are RangeError, not a generic Error
function parse(input: string): Result<number, RangeError> {
  const n = Number(input);
  return Number.isFinite(n)
    ? { ok: true, value: n }
    : { ok: false, error: new RangeError(`not a finite number: ${input}`) };
}

// Omit the second arg: E falls back to the default Error
function wrap(value: string): Result<string> {
  return { ok: true, value };
}

const good = parse('42');
const bad = parse('n/a');
console.log('good:', good.ok, good.ok && good.value);
console.log('bad:', bad.ok, !bad.ok && bad.error.message);
console.log('wrap:', wrap('payload').ok);

// Defaults compose: a Result inside pagination, both default params active at once
type Feed = Paginated<Result<string>>;
const feed: Feed = { items: [{ ok: true, value: 'a' }], nextCursor: null };
console.log('feed items:', feed.items.length, 'cursor:', feed.nextCursor);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

good: true 42
bad: false not a finite number: n/a
wrap: true
feed items: 1 cursor: null

How it works

Generic Defaults Fill Optional Type Arguments keeps everything in the functions parse and wrap.

The result comes back as an object carrying true.

Putting it to use

The primary signature is function parse(input: string)

The demo output is labeled (good:, bad:, wrap:), so each printed line can be matched to the operation producing it.

The call returns true.

Core lines

return { ok: true, value };
return Number.isFinite(n)
  ? { ok: true, value: n }

Interactive Tools for This Topic

FAQ

Does `parse` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `parse`, `wrap` at load time.