Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-31 07:28:30
Original
632 people have browsed it

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>
Copy after login

We would like to obtain an array of column names from this interface:

<code class="typescript">const IMyTable = ["id", "title", "createdAt", "isDeleted"];</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!