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
DDDOriginal
2024-10-29 09:31:30971browse

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>

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

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

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>

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!

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