Composition

Functional composition is a technique or pattern that allows us to combine multiple functions to create a more complex function.

The following code snippet declares a function used to trim a string and a function used to transform a piece of text in uppercase text:

const trim = (s: string) => s.trim();
const capitalize = (s: string) => s.toUpperCase(); 

We can create a function that performs both the preceding operations by composing them:

    const trimAndCapitalize = (s: string) => capitalize(trim(s));

The variable trimAndCapitalize is a function that invokes the trim function using s as its argument and passes its return to the capitalize function. We can invoke the trimAndCapitalize function as follows:

trimAndCapitalize(" hello ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.