0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. How do I still enforce an interface to the array of objects? I did readonly IData[] which converts the name to a string.
If you give data an explicit type, all information about the actual object you assigned to it will be lost. The only option is having a no-op generic function just for initialising the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.