Typing Functions
Parameters, optional arguments, and explicit return types.
The core of your logic
In TypeScript, you can add types to both the input parameters of a function and the output value (the return type).
This guarantees that the function receives what it expects, and the caller receives what was promised.
Preventing silent mistakes
If you don't explicitly type the return value, TypeScript will infer it based on what you return. While inference is smart, explicit return types are safer.
An explicit return type prevents you from accidentally returning early or returning the wrong variable due to a typo.
Syntax
typescript
// 1. Parameter Types & Explicit Return Type
function calculateTax(amount: number, rate: number): number {
return amount * rate;
}
// 2. Optional Parameters (?)
// The 'message' parameter can be string or undefined
function log(id: number, message?: string): void {
console.log(id, message);
}
Try it
Toggle the ? optional flag to see how it affects the function signature and the compiler's strictness.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Type parameters by adding
: Typeafter the parameter name. - Type the return value by adding
: Typeafter the parentheses. - Make parameters optional by adding a
?before the colon. - Optional parameters must always be at the end of the signature.
Done with this concept?
Mark it complete to track your progress. No login needed.