Annotating Functions and Variables

In the last lesson, npm run check found the booked-hours bug in the repair queue. It also reported errors about parameters that “implicitly” have an any type, and you left those alone. Those errors are the checker asking for information only you have.

In this lesson, you give it that information with type annotations. You’ll annotate what a function takes in and what it hands back, and you’ll see the checker hold both the function and every caller to what you wrote. Start with a small piece of Dee’s quote code, the function that prices labor.

Tell the Checker What Goes In

The checker can’t guess what a parameter is meant to hold, so it asks you. Spoke & Sprocket keeps every price in cents, and Dee charges 4500 cents, or $45, per hour of labor. Create a file named labor.ts in your repair-queue project folder, next to queue.ts, with her labor function as she wrote it in JavaScript:

Language: TypeScript Filename: labor.ts
export function laborCost(hours, hourlyRate) {
  const cents = hours * hourlyRate;
  return Math.round(cents);
}

Run the check you set up in the last lesson:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

labor.ts:1:27 - error TS7006: Parameter 'hours' implicitly has an 'any' type.

1 export function laborCost(hours, hourlyRate) {
                            ~~~~~

labor.ts:1:34 - error TS7006: Parameter 'hourlyRate' implicitly has an 'any' type.

1 export function laborCost(hours, hourlyRate) {
                                   ~~~~~~~~~~

...

Found 5 errors in 2 files.

Errors  Files
     2  labor.ts:1
     3  queue.ts:12

The check reads every .ts file in the project, so it also reports the three errors you left in queue.ts, one for each of the parameters of canBook(). They’re the same kind as the two new ones, and they have the same fix.

Read the first error from the left. labor.ts:1:27 is the file, line 1, and column 27, where hours starts. Nothing tells the checker what hours is, so it would fall back to any, a type that switches off checking for that value, and strict mode won’t let that happen silently. A later lesson looks at any up close. That’s all you need about any for now. It’s the type to keep out.

A type annotation fills the gap. It’s a colon and a type written after a name, and it tells the checker which values the name may hold.

The type names for JavaScript’s primitive values are lowercase, such as string, number, and boolean, and the same goes for null, undefined, bigint, and symbol.

Watch the capital letters: String is the type of a wrapper object that holds a primitive string, and tsc rejects it where a string is needed, reporting “‘string’ is a primitive, but ‘String’ is a wrapper object.”

Both of Dee’s parameters are numbers. Annotate them, and add a line that prices a brake service, which takes three-quarters of an hour:

Language: TypeScript Filename: labor.ts
export function laborCost(hours: number, hourlyRate: number) {
  const cents = hours * hourlyRate;
  return Math.round(cents);
}

console.log("Brake service:", laborCost(0.75, 4500));

That clears the two errors in labor.ts. Every parameter of canBook() is a number of hours, so open queue.ts and annotate line 12 the same way:

Language: TypeScript Filename: queue.ts
 1const repairQueue = [
 2  { bike: "Amara's commuter", hours: 1.5 },
 3  { bike: "Luis's road bike", hours: 3 },
 4  { bike: "Mei's cargo bike", hours: 2.5 },
 5];
 6
 7const bookedHours = repairQueue.reduce(
 8  (sum, ticket) => sum + (ticket.hours || 0),
 9  0,
10);
11
12function canBook(jobHours: number, booked: number, dayHours: number) {
13  return booked + jobHours <= dayHours;
14}
15
16console.log("Booked hours:", bookedHours);
17console.log("Fits a 3-hour job:", canBook(3, bookedHours, 8));

The .reduce() callback’s sum and ticket still need no annotations, because the checker works out their types from the call: ticket from the array and sum from the starting 0. Run the check again, then run the new file:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

$ node labor.ts
Brake service: 3375

The check is clean for both files, and JavaScript prints 3375 cents, or $33.75. Node.js strips both : number annotations before running the file, so the JavaScript that runs is Dee’s original function.

Promise What Comes Out

Annotations on the parameters tell the checker what goes in. The other half is what the function hands back, which matters most for an exported function that code in other files relies on. The quote script will add this labor cost to a parts total, so it needs a number. A return type annotation promises that. It goes after the parameter list’s closing parenthesis:

Language: TypeScript Filename: labor.ts
export function laborCost(
  hours: number,
  hourlyRate: number,
): number {
  const cents = hours * hourlyRate;
  return Math.round(cents);
}

console.log("Brake service:", laborCost(0.75, 4500));

The parameters now sit on their own lines for readability. cents has no annotation, because the checker works out its type from hours * hourlyRate, so : number there would only repeat it. A later lesson shows how far that goes.

The return type catches a change that breaks the promise. Say someone tidies the function and uses .toFixed(0) instead of Math.round(), a common way to round in JavaScript. Change the return line to try it:

Language: TypeScript
  return cents.toFixed(0);

Then run the check:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

labor.ts:6:3 - error TS2322: Type 'string' is not assignable to type 'number'.

6   return cents.toFixed(0);
    ~~~~~~

Found 1 error in labor.ts:6

.toFixed() returns a string, and the function promises a number. node labor.ts still prints Brake service: 3375, but that’s now the string "3375", and adding a chain’s 2499 cents to it would give "33752499".

Without : number after the parentheses, the checker would accept the function as one that returns a string, and the mistake would show up only in the file that used the result, if anywhere. Put Math.round(cents) back.

The same colon works on a variable that starts without a value. Dee charges more per hour for a rush job, so the rate gets its value in one of two branches. Add these lines above the console.log() call, and pass rate in place of 4500:

Language: TypeScript
const rushJob = false;
let rate: number;
if (rushJob) {
  rate = 6000;
} else {
  rate = 4500;
}

console.log("Brake service:", laborCost(0.75, rate));

The annotation requires every later value assigned to rate to be a number. rushJob stays bare, because the checker already works out its type from false. Run the check, and it stays clean.

To practice where annotations go, click the button below to have your mentor quiz you one question at a time. Answer in a sentence or a line of code.

Want to practice spotting where an annotation belongs?

Hold Callers to the Promise

The checker holds the code that calls the function to the same annotations. Dee asked an AI assistant for a line that prices one of her repair tickets, which record the bike and the hours a job took. Add the assistant’s two lines, highlighted here, to the bottom of labor.ts:

Language: TypeScript Filename: labor.ts
 1export function laborCost(
 2  hours: number,
 3  hourlyRate: number,
 4): number {
 5  const cents = hours * hourlyRate;
 6  return Math.round(cents);
 7}
 8
 9const rushJob = false;
10let rate: number;
11if (rushJob) {
12  rate = 6000;
13} else {
14  rate = 4500;
15}
16
17console.log("Brake service:", laborCost(0.75, rate));
18
19const ticket = { bike: "Trek FX 2", hours: 1.5 };
20console.log(ticket.bike, "labor:", laborCost(ticket, 4500));

At a glance, the suggestion reads well, since the ticket holds the job’s hours and laborCost() prices hours. Predict what npm run check reports and what node labor.ts prints, then run both and open the answer.

The check stops at the call (its long line wrapped for display):

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

labor.ts:20:46 - error TS2345: Argument of type
'{ bike: string; hours: number; }' is not assignable to parameter of type
'number'.

20 console.log(ticket.bike, "labor:", laborCost(ticket, 4500));
                                                ~~~~~~

Found 1 error in labor.ts:20

The text between the braces is the checker’s description of ticket, an object with a bike string and an hours number. That object lands in the hours parameter, which promises a number. The error points at ticket in the call, which is where the wrong value goes in.

Node.js doesn’t check types, so it runs the file anyway and prints a cost that isn’t a number:

Language: Shell
$ node labor.ts
Brake service: 3375
Trek FX 2 labor: NaN

Multiplying this ticket object by 4500 gives NaN in JavaScript, and nothing stops it at runtime, because the types are gone by then.

So the annotation is a promise in both directions. The function must return a number, and every caller must pass two numbers. The checker holds both sides to it before the code runs, and nothing does once it’s running. Change the call to laborCost(ticket.hours, 4500) and run both commands again. This time the check is clean, and JavaScript prints Trek FX 2 labor: 6750.

The promise covers only the types of values. If someone passes 90 minutes as laborCost(90, 4500), both arguments are numbers, so the check passes and the price is wrong. Annotations catch values of the wrong kind, and your own reading still has to catch the rest, as it does when you review AI-written code.

The button below starts a sentence about why that call passes. Finish it and send it, and your mentor tells you what your explanation gets right and what it misses.

Check Your Understanding

Try these before you open the answers:

  1. Annotate this function from the shop’s ticket printer, which labels a job for the workshop board:

    Language: TypeScript
    export function ticketLabel(bike, hours) {
      return `${bike} (${hours} h)`;
    }
    
  2. The workshop board also shows whether a bike can be worked on yet. Which variable in this snippet benefits from an annotation? Add it:

    Language: TypeScript
    const partsInStock = false;
    let jobStatus;
    if (partsInStock) {
      jobStatus = "ready to start";
    } else {
      jobStatus = "waiting for parts";
    }
    
  3. A teammate writes laborCost(1.5, "4500"). It returns 6750, the right price, but npm run check reports error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. Which side of the promise does the call break, and why fix it?

  1. Annotate both parameters and the exported function’s return type:

    Language: TypeScript
    export function ticketLabel(bike: string, hours: number): string {
      return `${bike} (${hours} h)`;
    }
    

    ticketLabel("Trek FX 2", 1.5) returns "Trek FX 2 (1.5 h)".

  2. jobStatus starts without a value, so an annotation requires every later value assigned to jobStatus to be a string: let jobStatus: string;. Write lowercase string, not String. partsInStock stays bare, because false already gives the checker its type.

  3. The caller breaks it, because "4500" is a string where hourlyRate promises a number. The price comes out right only because * converts the string to a number. Pass the same string to code that adds with +, and it joins text instead of adding cents, so the check flags the call before that can happen.

You now have an annotated labor cost function and a checker that holds it, and its callers, to its promise. In the next exercise, Exercise: Annotate the Labor Estimate, you’ll get the labor estimate Dee gives her customers through the check, so every estimate is a number the quote script can rely on.

It’s the course’s first coding exercise, and it runs in your browser. You change the file in the editor, then click Run Tests for automated feedback, and a failing test’s message tells you where to look. If you’re new to coding exercises on RealJS, then the Contents tab below the editor explains how they work.

Become a Member to join the conversation.