我在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());
有些人建议这样做,这是最简单的解决方案:
const properties: (keyof IMyTable)[] = ["id", "title", "createdAt", "isDeleted"];
然而,尽管这增加了一些类型安全性(我们不能错误地使用不存在的属性),但这并不是一个完全安全的解决方案,因为我们可能会错过一些属性并拥有重复的属性。所以我已经修复了这个问题,这个详细的解决方案是完全类型安全的,并防止了数组的编译时类型和运行时值之间的不一致:
const properties: [
keyof Pick<IMyTable, 'id'>,
keyof Pick<IMyTable, 'title'>,
keyof Pick<IMyTable, 'createdAt'>,
keyof Pick<IMyTable, 'isDeleted'>
] = ['id', 'title', 'createdAt', 'isDeleted'];
当然,这只适用于如果你不避免重复,但至少你只需要确保你正确地写所有属性一次(在Pick类型util),如果有任何错误,其余的将总是引发一个错误。我认为这是最健壮的解决方案中简单,容易理解和易读的解决方案。
问题是类型在运行时不可用。我最终定义了一个对象,并从该对象派生了类型。您仍然可以获得类型支持,并获得从单个位置获得所有键的列表的能力。
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"]