Curriculum
Course: TypeScript
Login
Text lesson

TS Functions

TypeScript provides specific syntax for defining the types of function parameters and return values.

Return Type

The return type of a function can be explicitly specified.

Example

// the `: number` here specifies that this function returns a number
function getTime(): number {
  return new Date().getTime();
}

If no return type is specified, TypeScript will infer it based on the types of the values or expressions returned.

Void Return Type

The void type can be used to signify that a function does not return any value.

Example

function printHello(): void {
  console.log(‘Hello!’);
}

Parameters

Function parameters use a similar syntax to variable declarations for typing.

Example

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

If no parameter type is specified, TypeScript defaults to any, unless additional type information is provided, as detailed in the Default Parameters and Type Alias sections below.

Optional Parameters

By default, TypeScript assumes all parameters are required, but you can explicitly mark them as optional.

Example

// the `?` operator here marks parameter `c` as optional
function add(a: number, b: number, c?: number) {
  return a + b + (c || 0);
}

Default Parameters

For parameters with default values, the default value is placed after the type annotation.

Example

function pow(value: number, exponent: number = 10) {
  return value ** exponent;
}

TypeScript can also infer the type from the default value.

Named Parameters

Typing named parameters follows the same pattern as typing regular parameters.

Example

function divide({ dividend, divisor }: { dividend: number, divisor: number }) {
  return dividend / divisor;
}

Rest Parameters

Rest parameters can be typed similarly to regular parameters, but the type must be an array, as rest parameters are always arrays.

Example

function add(a: number, b: number, ...rest: number[]) {
  return a + b + rest.reduce((p, c) => p + c, 0);
}

Type Alias

Function types can be defined separately from functions using type aliases.

Example

type Negate = (value: number) => number;

// in this function, the parameter `value` automatically gets assigned the type `number` from the type `Negate`
const negateFunction: Negate = (value) => value * –1;