Type Inference
Type Inference
π¨βπΌ TypeScript is smart about inferring types. You don't always need to write
them explicitlyβespecially for return types.
function add(a: number, b: number) {
return a + b // TypeScript knows this returns number
}
But TypeScript cannot infer parameter types (in most cases). You must
specify them:
// β Error: Parameter 'a' implicitly has 'any' type
function add(a, b) {
return a + b
}
// β
Correct
function add(a: number, b: number) {
return a + b
}
π¨ Open
and:
- Observe what TypeScript infers for each function
- Hover over function names to see the inferred return types
- Add an explicit return type where it catches a bug
This exercise uses: -
throw new Error(message) - stops execution and raises
an error - % (modulo operator) - returns the remainder after division (e.g.,
7 % 2 returns 1)π° In VS Code/Cursor, hover over a function name to see its full type signature.