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?
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 .
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).
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.
Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With