Typing functions
Functions are where types pay off most: they document exactly what goes in and what comes out, and they catch every caller that gets it wrong.
Parameters and return types
Return types can usually be inferred, but writing them on exported functions is good practice: it stops you from accidentally returning the wrong thing.
TypeScript reports: "Function lacks ending return statement and return type does not include 'undefined'." Add return 0; at the end to fix it.
Optional and default parameters
Inside the function, an optional parameter has the type string | undefined, so TypeScript makes you handle the missing case.
Rest parameters
Function types
Functions are values, so they have types too. This is essential for callbacks:
Notice that in ops, the arrow functions didn't need annotations. TypeScript used the contextual type MathOp. The same happens with .map, .filter, event handlers and so on.
Typing objects as parameters
You'll learn to name these object shapes with interface and type in the next lesson.
Async functions
An async function always returns a Promise<T>:
Overloads (briefly)
When a function behaves differently depending on its arguments, you can declare several signatures:
In practice, union types (next lessons) are often simpler than overloads.
Practice
Type this small cart module. Every function should have typed parameters and an explicit return type, and the last line should be an error.
1.What does greeting?: string mean in a parameter list?
2.What is the return type of async function getAge(): ... that returns a number?