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
index.ts
and:
  1. Hover over multiply and notice TypeScript infers its return type as number without an annotation
  2. On divide, add an explicit return type of : number so TypeScript flags the buggy string return
  3. Fix divide so dividing by zero throws an Error with the exact message "Cannot divide by zero" (instead of returning a string)
  4. Create isEven(n: number) that returns whether n is even; let TypeScript infer the boolean return type
  5. Export multiply, divide, and isEven

Required exports

multiply, divide, isEven

Completion criteria

  • multiply(4, 5) β†’ 20 (and other products work)
  • divide(10, 2) β†’ 5; divide(7, 2) β†’ 3.5
  • divide(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.

Please set the playground first

Loading "Type Inference"
Loading "Type Inference"
Login to get access to the exclusive discord channel.
Loading Discord Posts