TypeScriptBasic types

Function types

Typing parameters, the return value, and functions themselves as values.

On this page

Example

#
TypeScript
function formatPrice(amount: number, currency = 'USD', discount?: number): string {
  const final = discount ? amount * (1 - discount) : amount
  return `${final.toFixed(2)} ${currency}`
}

console.log(formatPrice(49))
console.log(formatPrice(100, 'USD', 0.2))
Result
49.00 USD
80.00 USD

Definition and usage

#

In a function, you type the parameters and, optionally, the return value: function add(a: number, b: number): number. With strict turned on, a parameter with no type causes an error, because it would implicitly get the type any.

You mark optional parameters with a question mark (title?: string), and you give default values just like in JavaScript (limit = 10). The compiler also checks the number of arguments at the call site.

An arrow type describes a function as a value: (value: string) => boolean. A type like that comes in handy for callbacks, event handlers, and passing functions into components.

Syntax

#
Syntax
function name(param: type, optional?: type): returnType { … }
type Fn = (param: type) => returnType

More examples

#
A function type as a parameter
TypeScript
type Validator = (value: string) => boolean

const isEmail: Validator = (value) => value.includes('@')
const notEmpty: Validator = (value) => value.trim().length > 0

function validate(value: string, rules: Validator[]): boolean {
  return rules.every((rule) => rule(value))
}

console.log(validate('emma@codeworlds.com', [notEmpty, isEmail]))
console.log(validate('   ', [notEmpty, isEmail]))
Result
true
false

Good practices

#
  • It’s worth writing the return type explicitly on exported functions. It guards against accidentally changing the contract.
  • Put optional parameters at the end of the list.

Related entries

#

Spotted a mistake or missing an example? Write to us.