𝗜𝗻𝘁𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝘁𝗼 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗧𝘆𝗽𝗲𝘀

TypeScript requires types for everything. This includes your functions. You must define types for inputs and outputs.

Function Syntax

You define input types and an output type like this:

function add(x: number, y: number): number { return x + y; }

TypeScript also uses type inference. You do not always need to write the output type. The compiler finds it for you.

If your function returns different types, TypeScript handles it. For example, if a function returns a number or a string, the compiler detects both.

Special Return Types

  • void: Use this when a function returns nothing.
  • never: Use this when a function throws an error or stops the program.

Parameters

You can make parameters optional using a question mark.

function makeProfile(name: string, age: number, url?: string) { // code }

You can also use default values. This makes a parameter optional without special symbols.

function makeProfile(name: string, age: number, url: string = "www.example.com") { return name + " visits " + url; }

Callback Functions

Functions are values. You can pass them as arguments. To define a callback type, use this syntax:

function makePage(func: (n: string, a: number, u?: string) => string, param1: string, param2: number) { func(param1, param2); }

The names of the parameters in the callback do not matter. Only the types matter.

Arrays of Functions

If you need a list of functions, define them as an array of that function type.

function applyMath(funcs: ((a: number, b: number) => number)[], x: number, y: number) { // code }

Rest Parameters

Use the spread operator to accept any number of arguments. This stores all inputs in an array.

function sum(...numbers: number[]) { // code }

sum(1, 2, 3);

Source: https://dev.to/jsha/introduction-to-typescript-function-types-hin