Home > Web Front-end > JS Tutorial > How Can I Get an Array of Interface Keys in TypeScript?

How Can I Get an Array of Interface Keys in TypeScript?

DDD
Release: 2024-10-29 09:31:30
Original
970 people have browsed it

How Can I Get an Array of Interface Keys in TypeScript?

Accessing Interface Keys as String Array in TypeScript

In TypeScript, it can be useful to obtain the property names of an interface as an array of strings. Consider the following interface:

<code class="typescript">export interface IMyTable {
  id: number;
  title: string;
  createdAt: Date;
  isDeleted: boolean;
}</code>
Copy after login

We would like to convert this interface into an array like this:

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

Iterating through the properties of an interface to extract the key names is not directly supported in TypeScript. However, there are solutions using custom transformers.

Using a Custom Transformer

As of TypeScript 2.4, custom transformers provide a way to modify TypeScript's behavior. We can define a custom transformer to extract interface keys.

<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

Limitations of Custom Transformers

Custom transformers have limitations. They require the use of the TypeScript transformation API instead of the traditional tsc command. There is an open issue requesting plugin support for custom transformers.

Other Considerations

If you are using a framework that generates interfaces dynamically, you may need to explore more advanced solutions, such as using a type utility library or a metaprogramming tool like Reflect.

The above is the detailed content of How Can I Get an Array of Interface Keys in TypeScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template