~/
hackweb.dev
TypeScript Arrays & Functions
Quiz
⌘K
...
~/
/tutorials
/ts/ts-arrays-functions/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/4ts-arrays-functions
Write
Preview
Diff
# TypeScript Arrays & Functions TypeScript makes arrays and functions type-safe with explicit element and parameter types. ## Typed Arrays ```typescript let numbers: number[] = [1, 2, 3]; let names: string[] = ["Alice", "Bob"]; let scores: Array<number> = [90, 85, 95]; // Readonly arrays let colors: readonly string[] = ["red", "green"]; // colors.push("blue"); // Error ``` **Remember:** Use `number[]` syntax — `Array<number>` is for complex nested types. ## Union Types in Arrays Arrays can hold multiple types: ```typescript let mixed: (string | number)[] = ["hello", 42]; mixed.forEach((item) => { if (typeof item === "string") { console.log(item.toUpperCase()); } else { console.log(item.toFixed(2)); } }); ``` ## Tuples Fixed types for each position: ```typescript let person: [string, number] = ["John", 25]; let pair: [string, number?] = ["single"]; // optional element ``` ## Function Parameters and Returns Always annotate parameters. Annotate return types for clarity: ```typescript function greet(name: string, age: number): string { return `Hello, ${name}. You are ${age}.`; } function double(x: number): number { return x * 2; } ``` **Tip:** TypeScript can infer simple return types, but be explicit for complex ones. ## Callback Functions Type callback parameters and return values: ```typescript function processItems( items: number[], callback: (item: number, index: number) => void ): void { items.forEach((item, index) => callback(item, index)); } processItems([1, 2, 3], (item, index) => { console.log(`Item ${index}: ${item}`); }); ``` **Remember:** Untyped callback parameters default to `any`. ## Array Methods with Types TypeScript tracks types through `map`, `filter`, `reduce`: ```typescript let numbers: number[] = [1, 2, 3, 4, 5]; let doubled: number[] = numbers.map((n) => n * 2); let evens: number[] = numbers.filter((n) => n % 2 === 0); let sum: number = numbers.reduce((acc, curr) => acc + curr, 0); ``` ## Best Practices - Use `readonly` for arrays that shouldn't change - Always type callback parameters - Use union types for mixed arrays instead of `any` - Annotate return types for complex functions ## Common Mistakes - Empty arrays without types = `any[]` - Forgetting callback parameter types - Using `any` for mixed arrays — use unions instead - Not annotating function return types
No changes yet
Reset to original
Submit suggestion
cancel