SyntaxStudy
Sign Up
TypeScript Primitive and Special Types
TypeScript Beginner 1 min read

Primitive and Special Types

TypeScript has a rich set of built-in types. The primitive types mirror JavaScript: string, number, bigint, boolean, symbol, null, and undefined. These types can be used as annotations anywhere a value is expected. TypeScript also adds several special types: any, unknown, never, and void, each with a distinct purpose and set of rules. The any type disables type checking for a value and should be avoided in well-typed code because it defeats the purpose of using TypeScript. The unknown type is the type-safe alternative to any — you can assign anything to unknown, but you must narrow the type before using the value. The never type represents values that never occur, such as the return type of a function that always throws or runs an infinite loop. The void type is used as the return type of functions that do not return a meaningful value. Unlike undefined, void signals intent — it tells callers not to rely on the return value. Understanding when to use null versus undefined, and how strictNullChecks changes their behavior, is fundamental to writing correct TypeScript.
Example
// Primitives
const name: string = "Alice";
const age: number = 30;
const big: bigint = 9007199254740993n;
const active: boolean = true;
const sym: symbol = Symbol("id");
const nothing: null = null;
const missing: undefined = undefined;

// any — escape hatch, avoid when possible
let wild: any = "hello";
wild = 42;
wild.foo.bar; // no error — dangerous

// unknown — type-safe any
let input: unknown = getUserInput();
// input.toUpperCase(); // Error — must narrow first
if (typeof input === "string") {
    console.log(input.toUpperCase()); // OK after narrowing
}

// never — unreachable code / exhaustive checks
function fail(message: string): never {
    throw new Error(message);
}

function assertNever(x: never): never {
    throw new Error(`Unexpected value: ${x}`);
}

// void — no meaningful return value
function logMessage(msg: string): void {
    console.log(msg);
    // returning undefined is allowed, returning a value is not
}

// Tuple — fixed-length typed array
const pair: [string, number] = ["Alice", 30];
const [user, score] = pair;

function getUserInput(): unknown { return "hello"; }