search

Home  >  Q&A  >  body text

Method to get the key of an interface or type as a string

<p>I have a Patient entity defined as an interface</p> <pre class="brush:php;toolbar:false;">export interface Patient { name: string; greeting: string; }</pre> <p>I want to create a header that will display each key in my Patient interface without having to modify them explicitly in the render function as I continue to add or remove keys to the interface. </p> <p>I’m thinking about the following pseudocode</p> <pre class="brush:php;toolbar:false;"><tr> keys of Patient.map((key) => <th>key.toString()</th>) </tr></pre> <p>The problem is, I can't seem to convert the pseudocode into actual code. I've tried using types and interfaces, and have been trying for a while, but I can't seem to understand the problem. </p> <p>I'm trying to improve my knowledge of Typescript and realize its potential in React, any help is greatly appreciated :)</p>
P粉884667022P粉884667022455 days ago551

reply all(1)I'll reply

  • P粉627136450

    P粉6271364502023-09-01 14:34:54

    The interface does not actually exist at runtime. They only exist during compilation and linting. Therefore, the interface's keys cannot be listed at runtime. The best you can do is create a dummy object for your interface:

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

    Then get the key of dummyPatient:

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

    reply
    0
  • Cancelreply