Given this type alias:
export type RequestObject = {
user_id: number,
address: string,
user_type: number,
points: number,
};
I want an array of all its properties, e.g:
['user_id','address','user_type','points']
Is there any option to get this? I have googled but I can get it only for interface using following package
https://github.com/kimamula/ts-transformer-keys
CodePudding user response:
You cannot do this easily, because of type erasure
Typescript types only exist at compile time. They do not exist in the compiled javascript. Thus you cannot populate an array (a runtime entity) with compile-time data (such as the RequestObject type alias), unless you do something complicated like the library you found.
Workarounds
- code something yourself that works like the library you found.
- find a different library that works with type aliases such as
RequestObject. - create an interface equivalent to your type alias and pass that to the library you found, e.g.:
import { keys } from 'ts-transformer-keys';
export type RequestObject = {
user_id: number,
address: string,
user_type: number,
points: number,
}
interface IRequestObject extends RequestObject {}
const keysOfProps = keys<IRequestObject>();
console.log(keysOfProps); // ['user_id', 'address', 'user_type', 'points']
