Typescript return object key based on input parameter

Viewed 442

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?

1 Answers

I would type it as playground :

function myFunction(name: string): {
    [x: string]: {};
} {
  // ....

  return {
    [`provide${name}`]: {},
    [`consume${name}`]: {},
  };
}

const { 
  provideTest,
  consumeTest,
} = myFunction('Test');

Unfortunately, you cannot generate a type based on the value of name.


As an alternative, you can ask the user to provide the keys, so the returned data would be strongly typed : playground.

In my opinion, the first way is better.

function myFunction<T extends string = string>(name: string): {
    [x in T]: {};
} {
  // ....

  return {
    [`provide${name}`]: {},
    [`consume${name}`]: {},
  } as {
    [x in T]: {};
  };
}

const { 
  provideTest,
  consumeTest,
} = myFunction<'provideTest' | 'consumeTest'>('Test');
Related