Search code examples
typescripttypescript-types

How to get all properties of type alias into an array?


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


Solution

  • 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

    1. code something yourself that works like the library you found.
    2. find a different library that works with type aliases such as RequestObject.
    3. 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']