Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys of a Typescript interface as array of strings

I've a lot of tables in Lovefield and their respective Interfaces for what columns they have.

Example:

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

I'd like to have the property names of this interface in an array like this:

const IMyTable = ["id", "title", "createdAt", "isDeleted"];

I cannot make an object/array based on the interface IMyTable directly which should do the trick because I'd be getting the interface names of the tables dynamically. Hence I need to iterate over these properties in the interface and get an array out of it.

How do I achieve this result?

like image 805
Tushar Shukla Avatar asked Oct 10 '22 05:10

Tushar Shukla


People also ask

How do you get the keys of a type in TypeScript?

How to get the keys of a TypeScript interface? To get the union of the keys of a TypeScript interface, we can use the keyof keyword. interface Person { name: string; age: number; location: string; } type Keys = keyof Person; to create the Keys type by setting it to keyof Person .

How do I iterate through interface TypeScript?

To iterate over interface properties in TypeScript, we can use the Object. keys method. const Activity = { id: "", title: "", body: "", json: {}, }; type Activity = typeof Activity; const headers: Array<Object> = Object. keys(Activity).

Can keys be strings in JavaScript?

Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.

Which keyword is used to access the interface in TypeScript?

Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.


1 Answers

As of TypeScript 2.3 (or should I say 2.4, as in 2.3 this feature contains a bug which has been fixed in [email protected]), you can create a custom transformer to achieve what you want to do.

Actually, I have already created such a custom transformer, which enables the following.

https://github.com/kimamula/ts-transformer-keys

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

interface Props {
  id: string;
  name: string;
  age: number;
}
const keysOfProps = keys<Props>();

console.log(keysOfProps); // ['id', 'name', 'age']

Unfortunately, custom transformers are currently not so easy to use. You have to use them with the TypeScript transformation API instead of executing tsc command. There is an issue requesting a plugin support for custom transformers.

like image 91
kimamula Avatar answered Oct 12 '22 19:10

kimamula