TypeScript Intermediate Introduction
TypeScript Intermediate deepens the concepts from the beginner course instead of teaching new first looks. Each lesson goes one level down into machinery, combinations and edge cases.
A check that passes and a value that is missing
The index into the record is typed as a plain number lookup. The checker accepts the program, yet the key is absent at runtime.
const stock: Record<string, number> = { pen: 4, ruler: 7 };
const count = stock['pencil'];
console.log(count + 1);The deepened fix widens, then narrows
The fix admits the lookup can miss and narrows the value before any arithmetic. Later narrowing lessons teach this pattern in depth.
const stock: Record<string, number> = { pen: 4, ruler: 7 };
const count: number | undefined = stock['pencil'];
if (count === undefined) {
console.log('pencil is not in stock');
} else {
console.log(count + 1);
}Example
function stockLevel(stock: Record<string, number>, item: string): string {
const count: number | undefined = stock[item];
if (count === undefined) {
return item + ': missing';
}
return item + ': ' + count;
}
const stock = { pen: 4, ruler: 7 };
console.log(stockLevel(stock, 'pen'));
console.log(stockLevel(stock, 'pencil'));Key points
- Generics gain multiple parameters, combined constraints, defaults and methods with their own type parameters.
- Type composition builds new types by joining unions and intersections in more precise ways.
- Narrowing lessons follow values through loops, callbacks and custom guard functions.
- Classes gain parameter properties, accessors, abstract templates and deeper implements checks.
- Mapped types and the built-in utility types reshape one object type into another.
- Unknown values get safe handling patterns that replace guessing with checks.
- Modules and compiler settings get their own depth pass near the end of the course.
In this example, the lookup result is widened to include undefined, so the missing key becomes a handled case instead of a silent NaN. The narrowing check then leaves a plain number in the second branch.
Note
Every code exhibit in this course is checked with the real compiler, including the errors.
Try it Yourself
Edit the code, then press Run.
Running is simulated Β· TypeScript Playground
Exercise
Why did the first stock program print NaN even though it passed the checker?