Created
February 21, 2022 14:23
-
-
Save adriangabardo/1ad729856eb13dbfe8ad39988bbf6bab to your computer and use it in GitHub Desktop.
A gist with examples of how to create a higher-order component that receives a method with a generic spread variable parameter, and how to type constrain said spread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example of a higher-order component with type-safety for functions with generic spread variables. | |
* In this example, the HOC is a function to create AWS Lambda (for AWS API Gateway) function handlers. | |
* All AWS Lambda exported handlers receive an (event, context) set of parameters. | |
* | |
* @author Adrian Gabardo <[email protected]> | |
*/ | |
type LambdaResponse = Promise<any | void>; | |
type BaseLambda = (event, context) => LambdaResponse; | |
/** | |
* A Lambda function that receives a generic/dynamic set of parameters (mixins). | |
* @param event - AWS Lambda event object | |
* @param context - AWS Lambda context object | |
* @param mixins - A tuple of generic typing for dynamic spread variable types | |
*/ | |
type MixedInLambda<T extends unknown[]> = (event, context, ...mixins: T) => LambdaResponse; | |
/** | |
* An HOC that returns methods ready for usage with AWS Lambda. | |
* @param handler - A custom function to be called by AWS Lambda. | |
* @param mixins - Generic spread variables. | |
* @returns - An AWS Lambda compatible function. | |
*/ | |
const create_aws_lambda = <T extends unknown[]>(handler: MixedInLambda<T>, ...mixins: T): BaseLambda => async (event, context): LambdaResponse => { | |
return await handler(event, context, ...mixins); | |
}; | |
/** | |
* EXAMPLE A ๐ | |
*/ | |
const squaredNumber = async (_event, _context, num: number) => { | |
return num * num; | |
}; | |
// This export is constrained to a second parameter of type number due to squaredNumber()'s parameter set. | |
export const squared_number_handler = create_aws_lambda(squaredNumber, 42); | |
/** | |
* EXAMPLE B ๐ | |
*/ | |
const jsonStringifyWithLogging = async (_event, _context, id: string, logger: typeof console) => { | |
const testObject = { test: true, id }; | |
logger.info("Stringifying:", testObject); | |
return JSON.stringify(testObject); | |
}; | |
// This export is constrained to a second parameter of string and a third of typeof console due to jsonStringifyWithLogging()'s parameter set. | |
export const json_stringify_handler = create_aws_lambda( | |
jsonStringifyWithLogging, | |
"1234-abcd", | |
console | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment