Course contentsShow
← TypeScript
Lesson 936 of 1,79621. The unknown TypeFree lesson

unknown for External Data Entry Points

Use unknown when data enters your system from outside: API responses, user input, file parsing, or third-party libraries.

unknown for External Data Entry Points

What you'll learn: Why unknown is the safest type for data entering your system from outside sources like APIs, user input, or third-party libraries.

The Boundary Problem

Your TypeScript code lives in a type-safe world, but the real world isn't typed. When data crosses the boundary from "outside" into your system — whether from an API response, a file upload, user form input, or a third-party library — you have zero compile-time guarantees about what you're actually receiving.

This is where unknown shines: it forces you to verify data at your system's entry points.

The Entry Point Rule

Use unknown when data enters your system from:

  • API responses – network data is inherently untyped
  • User input – forms, file uploads, clipboard data
  • File parsing – JSON, CSV, configuration files
  • Third-party libraries – especially JavaScript libraries without type definitions
  • Browser storage – localStorage, sessionStorage, cookies
  • Environment variables – process.env values

These are all untrusted data sources. TypeScript can't verify them at compile time, so treating them as unknown forces runtime validation.

The Safety Pattern

By typing external data as unknown, you create a validation checkpoint:

  1. Data arrives typed as unknown
  2. You cannot use it directly (TypeScript blocks you)
  3. You must narrow it with runtime checks
  4. Only then does it enter your type-safe domain

This pattern prevents the classic mistake of blindly trusting external data with any, which would let invalid data silently corrupt your application.

Key Takeaway: Always type external data entry points as unknown to enforce validation at your system's boundaries. This makes unsafe assumptions impossible and bugs visible at compile time.