如何将别名类型的所有属性放入数组中?

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

给定此类型别名:

export type RequestObject = {
    user_id: number,
    address: string,
    user_type: number,
    points: number,
};

我想要一个包含其所有属性的数组,例如:

['user_id','address','user_type','points']

有什么办法可以得到这个吗?我已经用谷歌搜索了,但我只能使用以下包

获取界面

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

因为type erasure

,你不能轻易做到这一点

Typescript 类型仅在编译时存在。它们不存在于已编译的 javascript 中。因此,您不能使用编译时数据(例如 RequestObject 类型别名)填充数组(运行时实体),除非您做一些复杂的事情,例如您找到的库。

解决方法

  1. 自己编写一些类似于您找到的库的代码。
  2. 找到一个使用类型别名的不同库,例如 RequestObject
  3. 创建一个与您的类型别名等效的接口,并将其传递给您找到的库,例如:
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']