0Pricing
TypeScript Academy · Lesson

Type-Safe Handling of unknown

Narrow unknown values before using them safely.

Working Safely With unknown

Typing external data as unknown is only half the job. The other half is narrowing it to a concrete type before use. This lesson covers the main narrowing techniques.

function describe(v: unknown): string {
  if (typeof v === 'string') return 'string: ' + v;
  if (typeof v === 'number') return 'number: ' + v;
  return 'other';
}
console.log(describe('hi'), describe(7), describe(true));

Narrowing With typeof

The typeof guard is the simplest tool. It narrows unknown to primitive types: string, number, boolean, function, object, and more.

function double(v: unknown): number {
  if (typeof v === 'number') {
    return v * 2; // v is number here
  }
  return 0;
}
console.log(double(21), double('no'));

All lessons in this course

  1. Understanding unknown vs any
  2. The never Type and Impossible States
  3. The void Type in Functions
  4. Type-Safe Handling of unknown
← Back to TypeScript Academy