~/
hackweb.dev
TypeScript Type Annotations
Quiz
⌘K
...
~/
/tutorials
/ts/ts-type-annotations/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/ts/2ts-type-annotations
Write
Preview
Diff
# TypeScript Type Annotations Type annotations explicitly tell TypeScript what type a value should be. ## Basic Syntax Use a colon after the variable name to specify the type: ```typescript let name: string = "John"; let age: number = 25; let isActive: boolean = true; ``` **Tip:** TypeScript can infer types automatically — annotations are optional when the type is obvious. ## Primitive Types TypeScript supports all JavaScript primitives: ```typescript let name: string = "John"; let age: number = 25; let isActive: boolean = true; let nothing: null = null; let missing: undefined = undefined; let bigNum: bigint = 9007199254740991n; let symbol: symbol = Symbol("id"); ``` ## The any Type `any` opts a value out of type checking: ```typescript let value: any = "Hello"; value = 42; // OK value = true; // OK ``` **Remember:** Only use `any` when migrating legacy code or dealing with truly unknown data. ## The unknown Type `unknown` is the type-safe alternative to `any`: ```typescript let value: unknown = "Hello"; // let str: string = value; // Error — must narrow first if (typeof value === "string") { console.log(value.toUpperCase()); // OK after narrowing } ``` **Tip:** Prefer `unknown` over `any` — it forces you to check the type. ## void and never `void` = no return value. `never` = function never returns. ```typescript function logMessage(msg: string): void { console.log(msg); } function throwError(msg: string): never { throw new Error(msg); } ``` ## Array Types Two syntaxes for typed arrays: ```typescript let numbers: number[] = [1, 2, 3]; let names: Array<string> = ["Alice", "Bob"]; // Readonly arrays let fixed: readonly number[] = [1, 2, 3]; // fixed.push(4); // Error ``` ## Tuple Types Tuples have fixed types per position: ```typescript let person: [string, number] = ["John", 25]; console.log(person[0].toUpperCase()); // "JOHN" // person[1].toUpperCase(); // Error: number has no toUpperCase ``` **Why tuples?** For data with a fixed structure like coordinates or database rows. ## Best Practices - Avoid `any` — use `unknown` or specific types - Always annotate function parameters and return types - Use `readonly` for arrays that shouldn't be modified - Let TypeScript infer when the type is obvious ## Common Mistakes - Using `any` excessively - Not annotating function return types - Forgetting `null` and `undefined` are different types in strict mode - `let arr = []` infers `any[]` — always give empty arrays a type
No changes yet
Reset to original
Submit suggestion
cancel