Last active
December 19, 2022 18:36
-
-
Save kayode-adechinan/5cc4ba50cd77bc91362e6f090328b0ab to your computer and use it in GitHub Desktop.
how to ensure that the output of a function has the same type of one of the function parameter
This file contains 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
import { z, ZodSchema } from 'zod'; | |
function createAdapter<T extends ZodSchema, U extends ZodSchema>( | |
options: { | |
input: T; | |
output: U; | |
}, | |
fn: (a: z.infer<T>) => Promise<z.infer<U>> | |
) { | |
return { | |
a: options.input, | |
b: options.output, | |
fn, | |
}; | |
} | |
// demo | |
// define input and output | |
const input = z.object({ | |
title: z.string().nullish(), | |
}); | |
const output = z.object({ | |
title: z.string().nullish(), | |
}); | |
// create adapter implementation | |
const demo = createAdapter({ input: input, output: output }, async (args) => { | |
return { | |
title: args.title?.toUpperCase(), | |
}; | |
}); | |
const test = async () => { | |
const result = await demo.fn({ title: 'hello' }); | |
console.log(result); | |
}; | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment