Method to get the key of an interface or type as a string
P粉884667022
2023-08-31 19:50:44
<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>
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:
Then get the key of
dummyPatient
: