Type Annotations

Explicitly tell TypeScript what type a value should be using a colon.

Syntaxlet isActive: boolean = true;

A type annotation is the : type you add after a variable, parameter, or return value. It tells TypeScript exactly what is allowed.

Where you can annotate

  • Variables: let x: number
  • Function parameters: function f(a: string)
  • Return types: function g(): boolean

If you assign a value of the wrong type, TypeScript reports an error during compilation.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • An API function annotates its parameter as string so callers know exactly what type to pass.
  • A shared utility module annotates every function return type so consumers see the contract in their IDE.
  • A database layer annotates query result variables so downstream code handles the right shape.

More examples

Variable and parameter annotations

Adds explicit colon-type annotations to variable declarations and to function parameters and return type.

Example · ts
let username: string = 'alice';
let age: number = 30;

function add(a: number, b: number): number {
  return a + b;
}

Annotating object properties

Uses an inline object type annotation to describe exactly which properties and types a variable must have.

Example · ts
let user: { name: string; age: number; active: boolean } = {
  name: 'Bob',
  age: 25,
  active: true,
};

Array annotation in function

Annotates a parameter as an array of numbers and the return as a number, covering array type annotation syntax.

Example · ts
function sumAll(numbers: number[]): number {
  return numbers.reduce((acc, n) => acc + n, 0);
}

const total: number = sumAll([1, 2, 3, 4, 5]);

Discussion

  • Be the first to comment on this lesson.