An array type describes its elements: number[] is a list of numbers, and Session[] is a list of Session records. Array<number> is equivalent to number[]. Choose one spelling consistently; this course uses the shorter form.
Annotate an empty array when you know its intended role: const sessions: Session[] = []. That gives later pushes a useful contract. A const array can still be mutated; const protects the binding, not its elements. We will make read-only contracts explicit later today.
An array can be empty or shorter than you expect. This course enables noUncheckedIndexedAccess, so reading items[0] includes undefined in its type. A number[] promises what present elements contain; it does not promise a first element exists. Guard the result before using it.
Array.find also returns a possible undefined because no match is a normal outcome. Check that outcome rather than adding a non-null assertion. A for/of loop gives you each actual element, avoiding a separate uncertain lookup.
Callbacks often infer their parameters from the array element type. In sessions.map(session => session.minutes), session is known to be Session. Do not repeat annotations that the surrounding context already supplies unless they clarify the contract.
Predict, check, then run
Before running, write down the output and explain which information the checker knows. Click Check types first, then Check & run.
const topics: string[] = ["Types", "Functions"];
const first = topics[0];
if (first !== undefined) {
console.log(first.toUpperCase());
}
const missing = topics.find(topic => topic === "Classes");
console.log(missing ?? "Not found");Enable JavaScript to edit and type-check this example.
Check your prediction
TYPES
Not found Read a real compiler error
The array element type is correct, but is the requested position present?
const topics: string[] = [];
console.log(topics[0].toUpperCase());Enable JavaScript to edit and type-check this example.
Check your diagnosis
The compiler warns that this element may be undefined. Store it and guard it before use, or provide a fallback. Writing topics[0]! would hide the warning without creating an element.
A known element type does not prove an element exists
string[] describes values that may be stored in the array. It does not say every numeric index is present, or that the array is nonempty. With checked indexed access, reading by position includes undefined and needs a guard.
For-of iterates the values actually present in an ordinary dense list and often avoids unnecessary indexing. Find still returns undefined when no match exists. Do not assert away missing values merely because the demonstration list happens to contain one.
function firstLabel(values: readonly string[]): string {
const first = values[0];
return first === undefined ? "Empty" : first.toUpperCase();
}
console.log(firstLabel([]));
console.log(firstLabel(["Types"]));Enable JavaScript to edit and type-check this example.
Check your prediction
Empty
TYPES The function states a useful empty-list behavior instead of promising an element for every input. Both paths are part of its contract.
const values: number[] = [];
let total = 0;
for (const value of values) {
total += value;
}
console.log(total);
console.log(values.find(value => value > 10) === undefined);Enable JavaScript to edit and type-check this example.
Check your prediction
0
true The total naturally handles no values. A search has a different output shape: it must communicate that no match was found.
Try the rule on new inputs
Run with empty, one-element and multi-element arrays. Try reading at length and explain why it is beyond the last valid position. Prefer a guard or fallback over a non-null assertion.
Your turn
Arrays & Safe Lookup: practise
Write firstLabel(topics: string[]): string. Return the uppercase first topic when it exists, otherwise “No topics”. Print ARRAYS and No topics for a populated and an empty array.
// Check an indexed lookup before calling a method.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
The declared element type does not establish that the array is nonempty.
Hint 2: a first step
Save topics[0] to a variable and compare it with undefined.
Show one solution
function firstLabel(topics: string[]): string {
const first = topics[0];
if (first === undefined) {
return "No topics";
}
return first.toUpperCase();
}
console.log(firstLabel(["Arrays"]));
console.log(firstLabel([]));Enable JavaScript to edit and type-check this example.
ARRAYS
No topicsExplain the types at the function boundary and the runtime checks, if any. Compare your approach before copying this answer.
Change it and explain it
Add a search for a particular topic and handle no match explicitly. Then compare indexed access with for/of: which gives you possibly missing data? Explain why checking types did not justify assuming that every list contains an item.
Completion is saved in this browser only. It does not measure mastery.