Typescript. Functions

with defining data types (e.g. annotations)
function add(a: number, b: number): number {
    return a + b;
}
without annotations
function add2(a, b)  {
    return a + b;
}
arrow functions
const add3 = (a, b) => {
    return a + b;
}

optional params

function getName(firstName: string, lastName?: string) {
const getCredentials = (name: string, family?: string): string => {
    return family ? (name + ' ' + family) : name;
}

default params

const getCredentials2 = (name: string, family: string = "Panteleev"): string => {
    return family ? (name + ' ' + family) : name;
}

Function Type Expressions

// --- function Type Expressions

type someFunctionType = (message: string) => void;
let greeter = (fn: someFunctionType) => {fn("Hello world")};

const writeInConsole = (s: string) => {
 console.log(s);
}

greeter(writeInConsole);

// --- another example with type expressions

type mathOperationType = (a: number, b: number) => number;

let calc = (a: number, b: number, mathOperation: mathOperationType) => {return mathOperation(a, b)}
let sum = (a, b: number) => {return a + b};
let subtract = (a, b: number) => {return a - b};

console.log('sum', calc(2, 2, sum));
console.log('sum', calc(2, 2, subtract));
This entry was posted in Без рубрики. Bookmark the permalink.