โ† TypeScript Foundations

Static Types

~290 words ยท 2 min read

Static Types in TypeScript

TypeScript adds static typing to JavaScript. Types are checked at compile time and then erased, so the output is plain JavaScript with zero runtime overhead.

Primitive Types

TypeScript mirrors JavaScript's primitives. The core ones are string, number, and boolean.

let username: string = "ada";
let age: number = 36;
let isActive: boolean = true;

Type Annotations vs Inference

You can annotate types explicitly, but TypeScript also infers types from initial values. When the type is obvious, omit the annotation and let inference do the work.

let count = 0;             // inferred as number
let name = "Ada";          // inferred as string
let items: string[] = [];  // annotation needed

any vs unknown

any disables type checking entirely โ€” it opts out of the type system. unknown is the type-safe counterpart: it accepts any value but forces you to narrow it before use.

let a: any = 10;
a.toUpperCase();   // allowed, but crashes at runtime

let u: unknown = 10;
// u.toUpperCase();   // error: Object is of type unknown
if (typeof u === "string") {
    u.toUpperCase();   // OK, narrowed to string

Avoid any. It silently disables the safety TypeScript provides. Prefer unknown when you genuinely cannot know a value's type, then narrow it with a type guard.

never

The never type represents values that never occur โ€” a function that always throws, an infinite loop, or the unreachable case after every union member has been handled.

function fail(msg: string): never {
    throw new Error(msg);
}

Why It Matters

Static types catch whole classes of bugs before runtime: typos in property names, wrong argument counts, null dereferences. They also power editor autocomplete and safe refactoring that plain JavaScript cannot offer.