TypeScript Tutorial menu

TypeScript Functions

In TypeScript you can give a type to each function parameter and to the value the function returns.

Parameter and Return Types

Example

typescript
function multiply(a: number, b: number): number {
  return a * b;
}

console.log(multiply(6, 7));
// multiply(6, "7");  // Error: Argument of type 'string' is not assignable to parameter of type 'number'
Output
42
  • a: number and b: number are the parameter types
  • : number after the brackets is the return type

TypeScript can usually infer the return type, but writing it helps you catch mistakes inside the function.

Wrong Number of Arguments

Unlike JavaScript, TypeScript checks how many arguments you pass:

Example

typescript
function greet(name: string): string {
  return "Hello " + name;
}

greet();               // Error: Expected 1 arguments, but got 0.
greet("Ali", "Khan");  // Error: Expected 1 arguments, but got 2.

Optional Parameters

Add ? after a parameter name to make it optional. Inside the function its type also includes undefined.

Example

typescript
function fullName(first: string, last?: string): string {
  if (last) {
    return first + " " + last;
  }
  return first;
}

console.log(fullName("Ayesha"));
console.log(fullName("Ayesha", "Malik"));
Output
Ayesha
Ayesha Malik

Optional parameters must come after required ones.

Default Parameters

A default value makes a parameter optional, and TypeScript infers its type from the value:

Example

typescript
function deliveryFee(city: string, express = false): number {
  const base = city === "Karachi" ? 150 : 300;
  return express ? base * 2 : base;
}

console.log(deliveryFee("Karachi"));
console.log(deliveryFee("Lahore", true));
Output
150
600

Rest Parameters

A rest parameter collects any number of arguments into a typed array:

Example

typescript
function total(...prices: number[]): number {
  return prices.reduce((sum, p) => sum + p, 0);
}

console.log(total(250, 120, 80));
Output
450

void Functions

If a function does not return anything, its return type is void:

Example

typescript
function logOrder(id: number): void {
  console.log(`Order ${id} received`);
}

Arrow Functions

Arrow functions are typed the same way:

Example

typescript
const square = (n: number): number => n * n;
const isAdult = (age: number): boolean => age >= 18;

console.log(square(9), isAdult(16));
Output
81 false

Function Types

You can describe the type of a function itself, for example for a callback:

Example

typescript
type PriceRule = (price: number) => number;

const tenPercentOff: PriceRule = p => p * 0.9;
const flatOff: PriceRule = p => p - 200;

function applyRule(price: number, rule: PriceRule): number {
  return rule(price);
}

console.log(applyRule(2000, tenPercentOff));
console.log(applyRule(2000, flatOff));
Output
1800
1800

Notice that p needs no annotation inside the arrow functions. TypeScript knows it is a number from the PriceRule type.

SyntaxMeaning
(x: number)Required parameter
(x?: number)Optional parameter
(x = 5)Default value, type inferred
(...x: number[])Rest parameter
(): voidReturns nothing
(n: number) => stringA function type

Turn on "strict": true in tsconfig.json. Then TypeScript also warns you about parameters with no type, instead of silently treating them as any.

Exercise

Exercise

How do you mark the parameter phone as optional?

Learn TypeScript with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp