Home  >  Article  >  Web Front-end  >  How Can I Extract an Array of Property Keys from a TypeScript Interface?

How Can I Extract an Array of Property Keys from a TypeScript Interface?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 07:28:30636browse

How Can I Extract an Array of Property Keys from a TypeScript Interface?

TypeScript Interface Property Keys as an Array

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.

Example Use Case

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>

Solution Using Custom Transformer

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn