Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does typescript allow calling keys of interface dynamically

I have a interface :

interface MyInterface {
   field_1 : string
   field_2 : string
   // ... other fields with a certain number
}

And I have a getter function that receives an instance of MyInterface and should retrieve a value of an attribute of this object dynamically

const myFactory = (myInstance:MyInterface):string => { 
    // Here some logic to retrieve a specific number 
    // for convenience lets say that the output of this logic is 1
    let output = 1
    return myInstance[`field_${output}`] // <=== This does not work since it calls a property of the interface dynmically
}

How can I call a property of an interface dynamically ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I saw the keyof operator :
but I am not sure how to use it here

>Solution :

You can try:

 const fieldKey = `field_${output}` as keyof MyInterface
 return myInstance[fieldKey]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading