NonNullable Strips null And undefined From Unions

Remove the nullable side of unions with NonNullable so lookup helpers can throw on absence and their return types still check out.

TypescriptData Integrity

Code

typescriptsnippet
33 lines
type Setting = { key: string; value: string };

const settings: Setting[] = [];

// The lookup may miss, so the honest return type includes undefined.
function findSetting(key: string): Setting | undefined {
  return settings.find((s) => s.key === key);
}

type Lookup = ReturnType<typeof findSetting>;
const isNullable: Lookup extends Setting | undefined ? true : never = true;

// NonNullable peels off null and undefined, keeping the rest of the union.
type Present<T> = NonNullable<T>;
type Narrowed = Present<Lookup>;
const isNarrowed: Narrowed extends Setting ? true : never = true;

// The classic use: assert-or-throw turns a nullable lookup into T.
function mustFind(key: string): NonNullable<Lookup> {
  const found = findSetting(key);
  if (found === undefined) {
    throw new Error(`missing setting: ${key}`);
  }
  return found;
}

settings.push({ key: 'retries', value: '3' });
const found = mustFind('retries');
console.log('value:', found.value);

const missing = findSetting('nope');
console.log('misses stay honest:', missing === undefined);
console.log('nullable side was:', isNullable, 'narrowed side is:', isNarrowed);

Output

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

value: 3
misses stay honest: true
nullable side was: true narrowed side is: true

How it works

The null-stripping work sits in findSetting and mustFind — everything else is wiring.

The failure path is explicit — Error is raised when the guard condition holds.

What to watch for

  • The imports (if any) point only at standard-library modules.
  • The guard found === undefined short-circuits the flow with an early throw when its condition holds.

Putting it to use

The main signature reads function findSetting(key: string)

The file announces each step in the output: value:, misses stay honest:, nullable side was:.

Core lines

return settings.find((s) => s.key === key);
throw new Error(`missing setting: ${key}`);

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
Validation comes first — `Error` marks the failure at `found === undefined`, before any partial work happens.
Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `findSetting`, `mustFind` at load time.