Parameter and return types

Beginner · 9 min

Why TypeScript needs you to annotate parameters but can usually work out return types itself, and when writing the return type anyway pays off.

Before thisType annotations and type inferenceany, unknown, never, and void

Net Ninja · 9 min

Parameter and return types

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Net NinjaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Parameters are the one place TypeScript has nothing to infer from, so a standalone function needs an annotation on each one; under `strict`, leaving it off is the `noImplicitAny` error rather than a silent `any`.
  • Return types are inferred from the `return` statements in the body, so annotating them is optional; the annotation turns the function's promise into a contract that is checked at the definition instead of at every caller.
  • Annotate the return type when a function is exported, has several return paths, or is recursive; leave it inferred for small local helpers and inline callbacks.
  • A function that returns nothing useful is typed `void`, and an annotated `void` return stops a stray `return value` from leaking a value callers might start relying on.
  • A destructured object parameter is annotated after the whole pattern, as in `({ name }: { name: string })`; writing `{ name: string }` inside the pattern renames the property instead of typing it.
  • A function passed directly where a function type is expected (such as the callback to `map`) gets its parameter types from that context, so it needs no annotations at all.

A function is a promise made to strangers

A function is written once and called from places its author may never see. In plain JavaScript, the only record of what calculateShipping expects is the parameter names and whatever the author remembered to put in a comment. Pass it a string where it wanted a number and you find out at runtime, if you find out at all — "5" * 2 is 10, but "5" + 2 is "52".

TypeScript’s answer is to make the function’s inputs and output part of its type. Once they are written down, every call site is checked against them, and the body is checked against them too. The function signature becomes a contract with two sides.

Parameters: the one place inference can’t help

Most of the time TypeScript works out types for you. const rate = 0.2 is a number because the value is right there. A parameter has no value at the point it is declared. It gets one only when some caller, possibly in another file, supplies it. So TypeScript asks you to say what it should be:

function addTax(price: number, rate: number) {
  return price * (1 + rate);
}

addTax(100, 0.2); // fine
addTax("100", 0.2); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

Leave the annotation off and, under strict, you get error 7006: “Parameter ‘price’ implicitly has an ‘any’ type.” That error comes from noImplicitAny, which strict turns on. Without it, the parameter would quietly become any and every check that depends on it would switch off.

Arrow functions use the same syntax. The parameter list is annotated exactly as above:

const formatPrice = (amount: number, currency: string) =>
  `${currency} ${amount.toFixed(2)}`;

Return types: inferred, unless you say otherwise

Hover over addTax in your editor and you’ll see function addTax(price: number, rate: number): number. You didn’t write that : number — TypeScript read it from the return statement. Return types are inferred from every return in the body, combined into a single type.

That inference is accurate, but it describes what the body does, not what you meant. Here is where the difference matters:

function parseQuantity(input: string): number {
  const n = Number(input);
  if (Number.isNaN(n)) {
    return "invalid"; // Error: Type 'string' is not assignable to type 'number'.
  }
  return n;
}

Without : number, this compiles. The inferred return type is number | "invalid", and the error surfaces later at some caller that tries to do arithmetic with the result — far from the actual mistake. With the annotation, the compiler checks the body against your intent and points at the bad line.

A reasonable rule of thumb:

  • Annotate exported functions (the contract other modules depend on), functions with several return paths, and recursive functions, where TypeScript often can’t infer a type that depends on itself and reports error 7023 instead.
  • Let it infer for short private helpers and inline callbacks, where the annotation is noise.

Functions that return nothing

A function called only for its side effect returns undefined at runtime, and TypeScript types it void. The void type was covered in the everyday-types group; the function-specific point is what an explicit void annotation enforces:

function logEvent(name: string): void {
  console.log(`[event] ${name}`);
}

function saveDraft(text: string): void {
  localStorage.setItem("draft", text);
  return text.length; // Error: Type 'number' is not assignable to type 'void'.
}

The second function would otherwise infer number, and callers would start depending on a return value you never meant to provide.

Destructured parameters

Object parameters are common, and they come with one trap. The annotation goes after the whole pattern:

function greet({ name, age }: { name: string; age: number }) {
  return `${name} is ${age}`;
}

Writing function greet({ name: string }) looks similar but means something else entirely. Inside a destructuring pattern, the colon renames: it pulls out name and binds it to a local variable called string. Nothing has a type, so strict reports that the binding string implicitly has an any type. For anything longer than two properties, give the shape a name with a type alias and annotate with that.

When the context does the work

One case needs no annotations. When a function is written directly where a function type is already expected, TypeScript reads the parameter types from that expectation:

const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.2); // p is number

This is called contextual typing. map declares that its callback receives an array element, so p is a number without you writing it. Pull the arrow function out into its own variable and the context is gone, and the annotation is needed again. You’ll see much more of this in the lesson on typing callbacks.

About the video

Net Ninja’s episode from his 2023 TypeScript crash course covers the same ground at a quick pace: annotating parameters on regular and arrow functions, typing a function that returns nothing as void, and how return types get inferred when you leave them off. It’s a good way to watch the editor’s hovers and red squiggles react in real time. The text above adds the parts the video only touches on: why parameters can’t be inferred, when an explicit return type earns its place, and the destructuring trap. Matt Pocock’s short video in the links below argues the “annotate or infer” question in more depth if you want a second opinion.

Check yourself

  1. 01Why can TypeScript infer the type of `const total = 0` but not the type of `price` in `function addTax(price) { ... }`?

    A variable's initializer tells the compiler exactly what value it starts with. A parameter has no value until some caller supplies one, and the callers may live in other files or not exist yet. Guessing from how the body uses `price` would be fragile, so TypeScript asks you to state the type, and under `strict` it reports an implicit `any` if you don't.

  2. 02If return types can be inferred, what does writing `: number` after the parameter list actually buy you?

    It moves the error to the right place. Without it, a body that accidentally returns `string | number` on one branch compiles fine and every caller downstream gets the wider type and complains. With the annotation, the compiler checks the body against what you meant and reports the bad `return` line itself.

  3. 03What is wrong with `function greet({ name: string }) { return name; }`?

    Inside a destructuring pattern, `name: string` means 'take the `name` property and bind it to a local variable called `string`'. There is no type annotation at all, so `strict` reports that `string` implicitly has an `any` type, and `name` is not even in scope. The type belongs after the pattern, as in `function greet({ name }: { name: string })`.

  4. 04Why does `[1, 2, 3].map((n) => n * 2)` compile under `strict` even though `n` has no annotation?

    This is contextual typing. `map` already declares that its callback receives an element of the array, so when the arrow function is written directly in that position TypeScript reads the parameter type from the expected function type. `n` is `number` without you writing it.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark