Skip to content

Latest commit

 

History

History
181 lines (108 loc) · 4.51 KB

File metadata and controls

181 lines (108 loc) · 4.51 KB

my-awesome-typescript-project


my-awesome-typescript-project / src/functional-programming

src/functional-programming

Functional programming.

Table of contents

1. Function type expressions for higher order functions

TypedFunction()

type TypedFunction<R, T> = (...args) => T;

Defined in: src/functional-programming.ts:20

Generic function type

Type Parameters

Type Parameter
R extends unknown[]
T

Parameters

Parameter Type
...args R

Returns

T


PromisifyFunction

type PromisifyFunction<T> = T extends TypedFunction<infer Z, infer X> ? (fn) => (...args) => Promise<Awaited<X>> : never;

Defined in: src/functional-programming.ts:26

Generic higher-order function type

Type Parameters

Type Parameter
T

TimeExecution

type TimeExecution<T> = T extends TypedFunction<infer Z, infer X> ? (fn) => (...args) => {
  duration: number;
  result: X;
} : never;

Defined in: src/functional-programming.ts:32

Another example

Type Parameters

Type Parameter
T

2. Typed higher order functions implementations

promisifySyncFn

const promisifySyncFn: PromisifyFunction<(...args) => string>;

Defined in: src/functional-programming.ts:41

Promisify sync function

Remarks

  • This pattern allows for static typing of hook-like functions.
  • The try / catch clause, promise resolution and rejection as well as parameter function call can be moved in any desired callback.

promisifyAsyncFn

const promisifyAsyncFn: PromisifyFunction<(...args) => Promise<number>>;

Defined in: src/functional-programming.ts:56

Promisify async function

Remarks

  • Same as the above using an async function type + async / await.

timeExecutionHook

const timeExecutionHook: TimeExecution<(...args) => number>;

Defined in: src/functional-programming.ts:72

Time function execution

Remarks

  • Hook-like higher order function that accepts a function as a parameter
  • It returns the return type of the function along with the execution duration

3. Typed higher order functions usage

promisedString

const promisedString: ReturnType<typeof promisifySyncFn>;

Defined in: src/functional-programming.ts:85

Usage: pass a sync function to a hook

Remarks

  • Use code narrowing in the param function to match wrapper declared type

promisedPromise

const promisedPromise: ReturnType<typeof promisifyAsyncFn>;

Defined in: src/functional-programming.ts:97

Usage: pass an async function to a hook

Remarks

  • Use code narrowing in the param function to match wrapper declared type

timedCountAllChars

const timedCountAllChars: ReturnType<typeof timeExecutionHook>;

Defined in: src/functional-programming.ts:111

Usage: pass an async function to a hook

Remarks

  • Use code narrowing in the param function to match wrapper declared type