Home > Enterprise >  How to get the keys of an interface or type as strings?
How to get the keys of an interface or type as strings?

Time:02-04

I have this Patient entity defined as an interface

export interface Patient {
  name: string;
  greeting: string;
}

I want to create a table head which is going to display each of the keys in my Patient interface without me having to explicitly modify them in the render function as I go ahead and add or remove keys from the interface.

I'm thinking about something like the following in pseudocode

<tr>
    keys of Patient.map((key) => <th>key.toString()</th>)
</tr>

The issue is I just can't seem to translate the pseudocode to actual code. I've tried using both types and interfaces and I've been at it for a while however I can't seem to be able to wrap my head around this.

I'm trying to get better versed with Typescript and use its potential in React, any help is greatly appreciated :)

CodePudding user response:

Interfaces do not really exist during runtime. These only exist during compilation and linting. Thus, there's no way to list down the keys of an interface during runtime. Best you can do is to create a dummy object for your interface:

const dummyPatient: Patient = {name: "", greeting: ""}

Then get the keys of the dummyPatient:

<tr>
    {Object.keys(dummyPatient).map((key) => <th>{key}</th>)}
</tr>
  • Related