Home > Enterprise >  Get function parameter from key in array of objects - Typescript
Get function parameter from key in array of objects - Typescript

Time:07-23

I have a function which takes an argument called functionName. functionName should always be the value of "Name" property from an array of objects. I skimmed through this but I was not able to achieve what I am looking for.

This is what I have.

const data = [{
  Name: 'functionA',
  EntryPoint: false,
  SystemOrClient: 'Client'
}, {
  Name: 'functionB',
  EntryPoint: false,
  SystemOrClient: 'Client'
}, {
  Name: 'functionC',
  EntryPoint: false,
  SystemOrClient: 'System'
}] as const;

const getSystemInfo = (functionName: string) => { //functionName should only accept values of Name property
//...
}


getSystemInfo('functionA') //should pass
getSystemInfo('functionAB') //should fail while compiling

Please help.

CodePudding user response:

You can get the type of data with the typeof operator. This can be indexed with number to get a union of all elements which you can index with the Name property.

const getSystemInfo = (functionName: typeof data[number]["Name"]) => {}

Playground

  • Related