my-awesome-typescript-project / src/functional-programming
Functional programming.
- 1. Function type expressions for higher order functions
- 2. Typed higher order functions implementations
- 3. Typed higher order functions usage
type TypedFunction<R, T> = (...args) => T;Defined in: src/functional-programming.ts:20
Generic function type
| Type Parameter |
|---|
R extends unknown[] |
T |
| Parameter | Type |
|---|---|
...args |
R |
T
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 Parameter |
|---|
T |
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 Parameter |
|---|
T |
const promisifySyncFn: PromisifyFunction<(...args) => string>;Defined in: src/functional-programming.ts:41
Promisify sync function
- 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.
const promisifyAsyncFn: PromisifyFunction<(...args) => Promise<number>>;Defined in: src/functional-programming.ts:56
Promisify async function
- Same as the above using an async function type + async / await.
const timeExecutionHook: TimeExecution<(...args) => number>;Defined in: src/functional-programming.ts:72
Time function execution
- 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
const promisedString: ReturnType<typeof promisifySyncFn>;Defined in: src/functional-programming.ts:85
Usage: pass a sync function to a hook
- Use code narrowing in the param function to match wrapper declared type
const promisedPromise: ReturnType<typeof promisifyAsyncFn>;Defined in: src/functional-programming.ts:97
Usage: pass an async function to a hook
- Use code narrowing in the param function to match wrapper declared type
const timedCountAllChars: ReturnType<typeof timeExecutionHook>;Defined in: src/functional-programming.ts:111
Usage: pass an async function to a hook
- Use code narrowing in the param function to match wrapper declared type