我在Lovefield中有很多表,以及它们各自的接口,说明它们有哪些列。

例子:

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

我想有这个接口的属性名在这样的数组中:

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

我不能直接基于接口IMyTable创建一个对象/数组,因为我将动态地获得表的接口名称。因此,我需要在接口中迭代这些属性,并从中获得一个数组。

我如何实现这个结果?


当前回答

不要将IMyTable定义为在接口中,而是尝试将它定义为一个类。在typescript中,你可以像接口一样使用类。

对于你的例子,像这样定义/生成你的类:

export class IMyTable {
    constructor(
        public id = '',
        public title = '',
        public createdAt: Date = null,
        public isDeleted = false
    )
}

使用它作为接口:

export class SomeTable implements IMyTable {
    ...
}

得到键:

const keys = Object.keys(new IMyTable());

其他回答

你需要创建一个类来实现你的接口,实例化它,然后使用Object.keys(yourObject)来获取属性。

export class YourClass implements IMyTable {
    ...
}

then

let yourObject:YourClass = new YourClass();
Object.keys(yourObject).forEach((...) => { ... });

在这个博客中

从数组中获取一个类型

现在我们可以使用typeof从animals数组中获取一个类型:

const animals = ['cat', 'dog', 'mouse'] as const
type Animal = typeof animals[number]

// type Animal = 'cat' | 'dog' | 'mouse'

下面需要你自己列出键,但至少TypeScript会强制IUserProfile和IUserProfileKeys拥有完全相同的键(Required<T>是在TypeScript 2.8中添加的):

export interface IUserProfile  {
  id: string;
  name: string;
};
type KeysEnum<T> = { [P in keyof Required<T>]: true };
const IUserProfileKeys: KeysEnum<IUserProfile> = {
  id: true,
  name: true,
};

问题是类型在运行时不可用。我最终定义了一个对象,并从该对象派生了类型。您仍然可以获得类型支持,并获得从单个位置获得所有键的列表的能力。

const myTable =  {
  id: 0,
  title: '',
  createdAt: null as Date,
  isDeleted: false,
};

export type TableType = typeof myTable;
export type TableTypeKeys = (keyof TableType)[];
export const tableKeys: TableTypeKeys = Object.keys(
  myTable
) as TableTypeKeys;

由上面产生的隐式类型将是(你可以用VSCode或其他高质量IDE检查):

type TableType = {
    id: number;
    title: string;
    createdAt: Date;
    isDeleted: boolean;
}

type TableTypeKeys = ("id" | "title" | "createdAt" | "isDeleted")[]

在运行时,你将能够访问tableKeys数组

console.log(tableKeys);
// output: ["id" , "title" , "createdAt" , "isDeleted"]

这应该可以

var IMyTable: Array<keyof IMyTable> = ["id", "title", "createdAt", "isDeleted"];

or

var IMyTable: (keyof IMyTable)[] = ["id", "title", "createdAt", "isDeleted"];