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 value.

Void (Non-value returning) functions

If we want to claim that the function will not return a value, we can use the special type void, which means “no value”:

Get hands-on with 1000+ tech skills courses.