Emmanuel Akinfulubi

TypeScriptError handling

Catch a TypeError from a missing function in TypeScript

2 Catch a call to something that does not exist

easy

Call a function that is not there and catch the resulting error, reporting your own message instead of the raw one.

Stuck? Three hints, smallest first
  1. 1. Calling a missing property gives a TypeError, not a plain Error.
  2. 2. TypeScript will refuse the obvious version at compile time, which is the point: you have to go through an untyped value to reach this bug.
  3. 3. Check the specific class with err instanceof TypeError so you handle only what you expect.

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

// TypeScript stops the obvious version:
//   const tools = {};
//   tools.missing();   // Property 'missing' does not exist on type '{}'.
//
// To reach this bug you have to lose the type first, which is exactly how it
// happens in real code: data arrives from JSON, or from an 'any' at a boundary.
const untyped: Record<string, unknown> = { present: () => 'I am here' };

function callByName(bag: Record<string, unknown>, name: string): string {
  const maybeFn = bag[name];
  if (typeof maybeFn !== 'function') {
    throw new TypeError(`${name} is not a function on this object`);
  }
  return String((maybeFn as () => unknown)());
}

function safely(name: string): string {
  try {
    return callByName(untyped, name);
  } catch (err) {
    if (err instanceof TypeError) return `no such tool: ${err.message}`;
    throw err;                    // anything unexpected keeps travelling
  }
}

console.log(safely('present'));
console.log(safely('missing'));

// What the raw failure looks like when nothing guards it:
let rawName = '';
try {
  (untyped['missing'] as () => void)();
} catch (err) {
  rawName = err instanceof Error ? err.constructor.name : 'unknown';
}

test('the real function is called', safely('present'), 'I am here');
test('the missing one is reported kindly', safely('missing'), 'no such tool: missing is not a function on this object');
test('the raw failure is a TypeError', rawName, 'TypeError');

Output


      

Worth noticing that TypeScript refuses the naive version of this exercise outright, so the interesting question becomes how an untyped value got in. The answer is always a boundary: JSON, a form, a library without types. Guard at the boundary, as callByName does, and the rest of your code stays typed.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.