Course outline · 0% complete

0/26 lessons0%

Course overview →

Annotating Functions

lesson 1-3 · ~11 min · 3/26

Parameters and return types

Functions are where types earn their keep. Annotate each parameter, then the return type after the parameter list:

function priceWithTax(price: number, taxRate: number): number {
  return price + price * taxRate;
}

Read it aloud: priceWithTax takes two numbers and returns a number. Now every mistake becomes a compile error:

  • priceWithTax("100", 0.2) fails, a string is not a number
  • priceWithTax(100) fails, an argument is missing
  • Returning "expensive" inside the body fails, that is not a number

In the JavaScript course you had to remember all of this in your head. Here the compiler remembers for you.

Code exercise · typescript

Run the typed function. Then try calling priceWithTax("100", 0.2) and run again to see the compiler reject the string.

Code exercise · typescript

A second worked example with a different return type. canVote returns the result of a comparison, which is already a boolean, so the annotation documents exactly what comes back. Run it, then change the return type to string and run again to see the mismatch reported inside the function body.

Quiz

Given function double(n: number): number, which call compiles?

What you must annotate, and what you may skip

Return types are usually inferred: if the body returns price + price * taxRate, TypeScript already knows the function returns a number. Many teams still write return types on exported functions as documentation.

Parameters are different. TypeScript cannot guess what callers will pass, so an unannotated parameter silently becomes type any, meaning unchecked. In strict mode (which every serious project turns on, and which you will meet in the final unit) that is the error Parameter 'x' implicitly has an 'any' type.

Rule of thumb: always annotate parameters, let everything else be inferred until you have a reason not to.

Code exercise · typescript

Your turn. Write describePet(name: string, age: number): string that returns a sentence like "Milo is 3 years old". Then print describePet("Milo", 3) and describePet("Luna", 7).