Skip to main content

Function TypeType to annotate Methods & Callback Function with implicit return of any

use function type annotations to

use ": void" for functions that

should return null/undefined

use ": [never](never)" for functions that

should never complete execution

function type inference

TSC only infers Type of return values, ignores Type of param args

TS annotate the following function:

const i = 42
const logNum = (i) => console.log(i)

const logNum: (i: number) => void = (i: number) => console.log(i) const logNum = (i: number): void => console.log(i)

const logNum: (i: number) => void = (i: number) => console.log(i)

void indicates that nothing is returned

TS annotate the following function:

const add = (a, b) => a + b;

const add = (a: number, b: number): number => a + b;

TS annotate destructured function params:

const logWeather = (forecast: { date: Date; weather: string }): void =>
console.log(forecast.date, forecast.weather);

const logWeather = ({date, weather}: { date: Date; weather: string }): void => console.log(date, weather);

Typed [Rest Parameter](rest-parameter)

TS Syntax for Rest Parameter which must always be of Type Array

Function Overload

Design Pattern to reuse multiple versions of same function with various Signatures

!gotcha f: Function implies unsafe return of any

!alt use Arrow Function ()⇒void as Type for annotating functions that will not be called

Typed Callback Function

Type Annotation for Anon Function pass as arg to function

Explicit Type Annotation for return Type not required since TSC does Type Inference

Parameter Default Value applies implicit Type Inference

const toString: (num: number) ⇒ string = (num: number) ⇒ String(num) equiv to

const toString: (num: number) => string = (num) => String(num);

equiv to

const toString = (num: number) => String(num);

callback function annotation

function stringify123(callback: (num: number) => string) {
return callback(123);
}

References