Want a faster signal before interviews? Take the Interview Ready Check →

DAY 13 OF 30

Typing Functions

Yesterday, in one sentence

What does as const do in TypeScript?

Interview question

What are literal types and where would you use them?

You add a type annotationType Annotation to a function parameter with a colon after its name. Parameters have to be annotated, because there is no value to infer from until the function is called.

function greet(name: string) {
  return `hello ${name}`;
}

greet("Jean"); // ok
greet(41); // ❌ Argument of type 'number' is not assignable to
//    parameter of type 'string'

You can also set the type for the value a function returns. This is called the return type, and you write it with a colon after the parameter brackets.

function level(name: string): number {
  return name.length;
}

TypeScript can read what you return and work the return type out for itself, so annotating it is optional.

const double = (level: number) => level * 2; // return type inferred as number

A ? after a parameter name makes it an optional parameter. This works like an optional property. The caller can leave the argument out, so inside the function the parameter is inferred as a union typeUnion Type of the declared type and undefined.

function recruit(team?: string) {
  // team is string | undefined
}

Setting a default value on a parameter makes it a default parameter. The argument can be left out and the parameter falls back to that value, so TypeScript always infers the type from the default value, as shown in the example below as a string.

function recruit(team = "mutants") {
  // team is string
}

A rest parameter collects any number of remaining arguments into an array, so it should be annotated with an array typeArray Type.

function assemble(...members: string[]) {
  // members is string[]
}

assemble("Scott", "Jean", "Logan");

Check yourself

In this function, what are the types of name and team?
function recruit(name = "hero", team?: string, ...powers: string[]) {}
How do you add types to a function in TypeScript?