In modern TypeScript development, it's common to encounter complex interfaces that define the structure of various data models. Often, there's a need to extract an array of property names from an interface to perform dynamic operations or create derived values.
Consider the following interface representing a database table:
<code class="typescript">export interface IMyTable { id: number; title: string; createdAt: Date; isDeleted: boolean; }</code>
We would like to obtain an array of column names from this interface:
<code class="typescript">const IMyTable = ["id", "title", "createdAt", "isDeleted"];</code>
Since TypeScript version 2.3 (with bug fixes in 2.4), custom transformers offer an elegant solution to this problem. Here's how you can use the "ts-transformer-keys" library:
<code class="typescript">import { keys } from 'ts-transformer-keys'; interface Props { id: string; name: string; age: number; } const keysOfProps = keys<Props>(); console.log(keysOfProps); // ['id', 'name', 'age']</code>
This approach requires using the TypeScript transformation API rather than running "tsc" directly. It's important to note that custom transformers are still in their early stages and may require additional configuration.
The above is the detailed content of How Can I Extract an Array of Property Keys from a TypeScript Interface?. For more information, please follow other related articles on the PHP Chinese website!