Function Types (signatures) in TypeScript

Description

This is used to describe the general structure of a function, the argument it takes in and the type of data it returns.

// example 1
let greet: (a: string, b: string) => void;
greet = (name: string, greeting: string) => {
    console.log(`${name} says ${greeting}`)
}
greet('oge', 'hi');

//example 2
let calc: (a: number, b: number, c: string) => number;

calc = (numOne: number, numTwo: number, action: string) => {
    if (action === 'add') {
        return numOne + numTwo;
    } else {
        return numOne - numTwo;
    }
}

//example 3
let logDetails: (obj: { name: string, age: number }) => void;
logDetails = (ninja: { name: string, age: number }) => {
    console.log(`${ninja.name} is ${ninja.age} years old`)
}
logDetails({ name: 'bolu', age: 2 })

//using type aliases with example 3;
let logDetails: (obj: { name: string, age: number }) => void;

type person = { name: string, age: number };

logDetails = (ninja: person) => {
    console.log(`${ninja.name} is ${ninja.age} years old`)
}
logDetails({ name: 'bolu', age: 2 })

No Comments Yet