Home > Web Front-end > JS Tutorial > How Can I Get the Keys of a TypeScript Interface as a String Array?

How Can I Get the Keys of a TypeScript Interface as a String Array?

Linda Hamilton
Release: 2024-10-29 19:04:30
Original
605 people have browsed it

How Can I Get the Keys of a TypeScript Interface as a String Array?

Keys of a Typescript Interface as String Array

One common scenario in TypeScript development is handling a database table interface and its respective columns. For instance, consider an interface defined as:

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

One may need to retrieve the property names of this interface as an array of strings, like:

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

This is particularly essential when dynamically accessing table interfaces where direct object/array assignment is not feasible.

Solution

To achieve this, one can employ a custom transformer introduced in TypeScript 2.3, available as a third-party package:

<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 transformer requires utilizing the TypeScript transformation API instead of directly invoking the tsc command. However, there is an ongoing issue requesting plugin support for custom transformers to simplify their usage.

The above is the detailed content of How Can I Get the Keys of a TypeScript Interface as a String Array?. 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