我在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());

其他回答

下面需要你自己列出键,但至少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,
};

从TypeScript 2.3(或者我应该说2.4,因为在2.3这个特性包含一个bug,该bug已在typescript@2.4-dev中修复)开始,你可以创建一个自定义转换器来实现你想要做的事情。

实际上,我已经创建了这样一个自定义转换器,它支持以下功能。

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

import { keys } from 'ts-transformer-keys';

interface Props {
  id: string;
  name: string;
  age: number;
}
const keysOfProps = keys<Props>();

console.log(keysOfProps); // ['id', 'name', 'age']

不幸的是,定制变压器目前还不太容易使用。你必须将它们与TypeScript转换API一起使用,而不是执行tsc命令。有一个问题,要求插件支持自定义变压器。

有些人建议这样做,这是最简单的解决方案:

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),如果有任何错误,其余的将总是引发一个错误。我认为这是最健壮的解决方案中简单,容易理解和易读的解决方案。

// declarations.d.ts
export interface IMyTable {
      id: number;
      title: string;
      createdAt: Date;
      isDeleted: boolean
}
declare var Tes: IMyTable;
// call in annother page
console.log(Tes.id);

在这个博客中

从数组中获取一个类型

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

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

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