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 foundRead 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
TYPESThe 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
trueThe 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.
Debug a plausible mistake
Repair an honest empty result type
first must accept an empty number array without inventing a value. Print 2 for [2,3], then true for the empty result being undefined. Keep indexed-access checking enabled.
Use Check types to inspect the genuine diagnostic before repairing the code. Keep the intended contract; do not bypass the checker with any, a broad assertion or an ignore comment.
function first(values: readonly number[]): number {
return values[0];
}
console.log(first([2, 3]));
console.log(first([]) === undefined);Enable JavaScript to edit and type-check this example.
Hint 1: the idea
A general array may have no position zero.
Hint 2: a first step
Expose possible absence in the return type rather than adding a non-null assertion.
Show one solution
function first(values: readonly number[]): number | undefined {
return values[0];
}
console.log(first([2, 3]));
console.log(first([]) === undefined);2
trueWith indexed-access checking on, values[0] has type number | undefined, so TS2322 rejected returning it as a plain number. The fix changes no runtime code: it makes the signature admit what [][0] already does at runtime. Callers now have to handle undefined, which is exactly the decision a non-null assertion (values[0]!) would have hidden.
Your turn
Arrays & Safe Lookup: practice
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 topicstopics[0] is string | undefined even though the parameter is string[], so calling .toUpperCase() on it directly fails with TS2532. Saving it in first and returning early on undefined narrows first to string for the last line. The empty array is the runtime case that would otherwise have thrown.
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.