TypeScript Types: Annotations, Unions, and Inference

Published Updated

Types describe the values your TypeScript code expects. This topic covers the type system from the first annotation to the point where you can model real application data: primitives and objects, named shapes, unions with narrowing, and the safe handling of data you have not verified yet.

The four guides below build on each other in order. If you have never written a TypeScript annotation, start at the top. If you already write annotations comfortably, jump straight to unions and narrowing, which is where the type system starts doing work JavaScript cannot.

TypeScript Types Topics

Do TypeScript Types Run as JavaScript?

TypeScript type annotations do not run as JavaScript. The compiler checks them and removes them from the output. Compare this TypeScript file with its JavaScript output:

// input: user.ts
type User = { id: string; name: string };

const user: User = { id: "u1", name: "Ada" };
console.log(user.name);
// output: user.js, after running tsc
const user = { id: "u1", name: "Ada" };
console.log(user.name); // prints: Ada

The type declaration and the annotation vanished entirely. This erasure is why types cost nothing at runtime, and it is also why they cannot protect you from data that arrives at runtime. Validate external data before using it as a typed value.

Some TypeScript features also generate runtime code. Regular enum declarations create objects, and namespaces containing values can generate JavaScript. Type-only declarations disappear; the exact output depends on the feature and compiler settings.

Frequently Asked Questions

Do TypeScript types exist when the code runs?

TypeScript annotations, interfaces, aliases, and unions do not exist at runtime. They are erased before JavaScript runs. Some TypeScript features, such as regular enums and namespaces containing values, generate JavaScript instead of disappearing.

Do you have to annotate every value in TypeScript?

You do not need to annotate every value in TypeScript. The compiler can infer many types from assignments and function calls. Add annotations where inference has too little information or where an explicit type helps callers, such as function parameters and public return types.

Can TypeScript types validate API data?

TypeScript types cannot validate API data at runtime. Check the response with JavaScript validation code or a schema validator before treating it as the expected type.

Continue Learning TypeScript

  • Return to the TypeScript guide for the full language overview, including generics, tsconfig, and tooling.
  • Review the JavaScript guide if the runtime side of the language still feels shaky.
  • Still deciding whether types are worth it? JavaScript vs TypeScript walks the trade directly.

Sources

  1. [1]
    The Basics
    (typescriptlang.org)
  2. [2]
    Everyday Types
    (typescriptlang.org)
  3. [3]
    TSConfig Reference
    (typescriptlang.org)