Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Created January 30, 2024 18:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clhenrick/15b3fd15a1add8a3b9c6e4b92962cd1f to your computer and use it in GitHub Desktop.
Save clhenrick/15b3fd15a1add8a3b9c6e4b92962cd1f to your computer and use it in GitHub Desktop.
Example of using a TypeScript generic type in a function's parameter and return type
// MyType is a generic that we can pass different types when calling handleAsyncTask()
const handleAsyncTask = async function<MyType> (asyncFn: () => Promise<MyType | string>) : Promise<[boolean, MyType | undefined]> {
const result = await asyncFn();
if (typeof result === 'string') {
return [true, undefined];
}
return [false, result];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment