"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve the Keys of a TypeScript Interface as an Array of Strings?

How to Retrieve the Keys of a TypeScript Interface as an Array of Strings?

Published on 2024-11-16
Browse:153

How to Retrieve the Keys of a TypeScript Interface as an Array of Strings?

Accessing Keys of a Typescript Interface as an Array of Strings

Introduction

Working with tabular data in Typescript requires the use of interfaces to define column structures. To efficiently manipulate these structures, it is often necessary to retrieve the property names of these interfaces as an array of strings.

Solution

Using Custom Transformers

Since Typescript version 2.4, custom transformers provide a mechanism to extract keys from interfaces. Consider the following interface:

interface IMyTable {
  id: number;
  title: string;
  createdAt: Date;
  isDeleted: boolean;
}

To obtain the property names as an array:

import { keys } from 'ts-transformer-keys';

const IMyTable = keys();

console.log(IMyTable); // ["id", "title", "createdAt", "isDeleted"]

Limitations of Custom Transformers

While custom transformers offer a convenient solution, they require the use of the Typescript transformation API rather than the ts command. This limitation can hinder their usability.

Alternatives

In scenarios where custom transformers are not feasible, alternative options include:

  • Using reflection techniques (not recommended for performance reasons)
  • Explicitly specifying the array of property names (prone to human error and maintenance overhead)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3