Search⌘ K
AI Features

Functions and Type Annotations

Explore how to add type annotations to functions in TypeScript to improve code safety. Understand function parameters, return types, optional and default arguments, and how to type functions passed as variables. This lesson helps you write clearer, error-resistant code using TypeScript's static typing features.

Functions also get to participate in the static-typing fun. The parameters and return values can have type annotations and the function as a whole has its own static type.

Function parameters

TypeScript function parameters can have type annotations, with a similar syntax to what we’ve seen for variable declarations. The annotations work whether the function is a named function, an anonymous function, or a class method. All three of these examples have the same typing:

//1
function priceOfTicket(row: number, accessType: string) : number { }

//2
let priceOfTicket = function(row: number, accessType: string) : number { }

//3
class Ticket {
  priceOfTicket(row: number, accessType: string) : number { }
}

In all three cases, the function priceOfTicket expects two arguments: a number first and a string second. It then returns a number.

Let’s talk about the return type first. As it’s currently written, all three of these functions would fail compilation because they claim to return a number, but currently they don’t return anything. The TypeScript compiler will not compile a function that sets a return type but does not return a ...