I want to write a function that accepts a name parameter and then use it to create return object property names:
function myFunction (name: string) {
// ....
return {
[`provide${name}`]: {},
[`consume${name}`]: {}
}
const { provideTest, consumeTest } = myFunction('Test')
How should I type this function?
You can type it like this (playground link):
type ProvideConsumeObj<T extends string> = Required<{
[key in (`provide${T}` | `consume${T}`)]: object
}>;
function myFunction<T extends string>(name: T): ProvideConsumeObj<T> {
// ....
return {
[`provide${name}`]: {},
[`consume${name}`]: {},
} as ProvideConsumeObj<T>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With