Lesson 101 of 296
Typing arrays, objects and functions
What you will learn
- Array and tuple types
- Readonly arrays
- Object types, optional and readonly properties
- Index signatures and Record
- Function types, optional and default parameters, void
- Function type expressions and overloads
On this page
Arrays
const scores: number[] = [72, 85];
const names: Array<string> = ["Sam", "Ali"]; the same, written as a generic
const mixed: (string | number)[] = ["a", 1];Both number[] and Array<number> are fine. Most code uses number[].
Tuples
A tuple is an array with a fixed length and a type for each position.
const point: [number, number] = [10, 20];
const entry: [string, number] = ["Sam", 30];
const user: [id: number, name: string] = [1, "Sam"]; labelled tuple elementsReact's useState returns a tuple: [value, setValue].
Readonly arrays
const ids: readonly number[] = [1, 2, 3];
ids.push(4); Error: Property 'push' does not exist on type 'readonly number[]'.ReadonlyArray<number> is the same. Use readonly arrays for parameters your function should not change.
Object types
const user: { name: string; age: number } = { name: "Sam", age: 30 };Usually you give the shape a name with type or interface (Lesson 104):
type User = {
id: number;
name: string;
email?: string; optional: may be missing
readonly createdAt: Date; cannot be changed after creation
};email?: stringmeans the property can be missing. Its type isstring | undefined.readonlystops assignment:user.createdAt = new Date()is an error.
Excess property checks
When you write an object literal directly where a type is expected, TypeScript complains about extra properties, because they are probably typos:
const u: User = { id: 1, name: "Sam", createdAt: new Date(), emial: "x" };
Error: Object literal may only specify known properties, and 'emial' does not exist in type 'User'.Index signatures and Record
For objects with any number of keys of the same type:
const stock: { [productId: string]: number } = { kettle: 4, mug: 12 };
const prices: Record<string, number> = { kettle: 2999 };Record<K, V> is a utility type (Lesson 111) meaning "an object whose keys are K and values are V". With a union of keys, every key is required:
type Role = "admin" | "editor" | "viewer";
const labels: Record<Role, string> = {
admin: "Administrator",
editor: "Editor",
viewer: "Viewer"
};Forgetting one role is an error. This is a great way to make sure every case is handled.
Functions
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}`;
}
function log(message: string, level?: "info" | "error"): void {
console.log(level ?? "info", message);
}- Parameters are typed one by one.
?makes a parameter optional; optional parameters must come after required ones.- A default value also makes it optional, and its type is inferred from the default.
voidmeans "this function does not return a useful value".
Arrow functions:
const double = (n: number): number => n * 2;Rest parameters:
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}Function types
To describe a function value, such as a callback:
type Formatter = (value: number) => string;
const toPounds: Formatter = (pence) => `£${(pence / 100).toFixed(2)}`;
function applyAll(values: number[], format: Formatter): string[] {
return values.map(format);
}In toPounds, pence gets its type from Formatter. This is called contextual typing.
Typing callbacks: void return
type OnSave = () => void;A function type returning void can be given a function that returns something; the result is just ignored. That is why [1, 2].forEach((n) => list.push(n)) is allowed even though push returns a number.
Overloads (brief)
When one function accepts different argument patterns with different return types, you can list several overload signatures:
function parse(value: string): number;
function parse(value: number): string;
function parse(value: string | number): string | number {
return typeof value === "string" ? Number(value) : String(value);
}Use overloads rarely; unions or generics (Lesson 109) are usually clearer.
Common mistakes
- Confusing
email?: string(may be missing) withemail: string | undefined(must be present, but can be undefined). - Using
Functionorobjectas types; they are too loose. - Putting optional parameters before required ones.
- Using index signatures where a specific object type would catch typos.
How to say it in an interview
"I type arrays as T brackets, tuples for fixed positions like useState, and readonly arrays for inputs I should not mutate. Object types can have optional and readonly properties, and object literals get excess property checks that catch typos. For dictionaries I use Record, and Record with a union of keys forces every key to be present. Functions get typed parameters and return types, with optional and default parameters, and I name callback shapes with function type aliases."
Key words
| Word | Meaning |
|---|---|
| Tuple | A fixed-length array with a type per position |
| Optional property | name?: type; may be missing |
| readonly | Cannot be reassigned |
| Index signature | A type for any key: [key: string]: V |
| Record | A utility type for objects with keys K and values V |
| void | A function returns nothing useful |
| Contextual typing | Types inferred from where a value is used |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.