TypeScript
Beginner
1 min read
Primitive and Special Types
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"; }
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript