SyntaxStudy
Sign Up
TypeScript TypeScript Compilation and the Type System
TypeScript Beginner 1 min read

TypeScript Compilation and the Type System

TypeScript uses a structural type system, which means type compatibility is determined by the shape of a value rather than its explicit declaration. If two types have the same properties and methods, they are considered compatible even if they were declared independently. This is sometimes called duck typing and is different from the nominal type systems found in languages like Java or C#. The compilation process involves type-checking your source files and then erasing all TypeScript-specific syntax to produce clean JavaScript. Types have zero runtime cost — they exist only during development and compilation. This means TypeScript does not add any overhead to your running application. TypeScript's type inference engine is powerful enough that you often do not need to write explicit type annotations. The compiler can infer the type of variables from their initializers, the return type of functions from their return statements, and the types of function parameters in many callback scenarios. Writing annotations where inference already works is considered noise; the goal is to annotate where inference cannot determine the correct type.
Example
// Structural typing — shape matters, not name
interface Point2D {
    x: number;
    y: number;
}

interface Coordinate {
    x: number;
    y: number;
}

// Compatible because shapes match
const pt: Point2D = { x: 1, y: 2 };
const coord: Coordinate = pt; // OK — same shape

// Excess property check (only on object literals)
// const bad: Point2D = { x: 1, y: 2, z: 3 }; // Error

// Type inference — no annotations needed here
const message = "Hello";          // string
const count = 42;                 // number
const items = [1, 2, 3];         // number[]
const double = (n: number) => n * 2; // (n: number) => number

// Widening — union returned from branches
function getStatus(code: number) {
    if (code === 200) return "ok";
    if (code === 404) return "not found";
    return "error";
} // return type inferred as string

// Type erasure — compiled JS has no types
// TypeScript:  const x: number = 5;
// JavaScript:  const x = 5;

console.log(double(count)); // 84