Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript return object key based on input parameter

Tags:

typescript

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?

like image 331
Mohammad Ataei Avatar asked Jun 24 '26 21:06

Mohammad Ataei


1 Answers

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>;
}
like image 148
Maccesch Avatar answered Jun 27 '26 10:06

Maccesch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!