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:
- Hover over
multiplyand notice TypeScript infers its return type asnumberwithout an annotation - On
divide, add an explicit return type of: numberso TypeScript flags the buggy string return - Fix
divideso dividing by zero throws anErrorwith the exact message"Cannot divide by zero"(instead of returning a string) - Create
isEven(n: number)that returns whethernis even; let TypeScript infer the boolean return type - Export
multiply,divide, andisEven
Required exports
multiply, divide, isEvenCompletion criteria
multiply(4, 5)β20(and other products work)divide(10, 2)β5;divide(7, 2)β3.5divide(10, 0)throws with message"Cannot divide by zero"isEven(4)/isEven(0)βtrue;isEven(7)βfalse
throw new Error(message) stops normal execution and raises an error. For
isEven, choose an arithmetic check that works for positive, negative, and
zero values.π° In VS Code/Cursor, hover over a function name to see its full type signature.


