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>
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>
This is particularly essential when dynamically accessing table interfaces where direct object/array assignment is not feasible.
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>
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!