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

例子:

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

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

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

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

我如何实现这个结果?


当前回答

这是一个艰难的问题!谢谢大家的帮助。

我的需要是将接口的键作为字符串数组来简化mocha/chai脚本。不关心在应用程序中使用(还),所以不需要创建ts文件。感谢ford04的帮助,他上面的解决方案是一个巨大的帮助,它的工作完美,没有编译器黑客。下面是修改后的代码:

选项2:基于TS编译器API的代码生成器(TS -morph)

节点模块

npm install --save-dev ts-morph

keys.ts

注意:这里假设所有ts文件都位于./src的根目录下,并且没有子文件夹,请相应地调整

import {
  Project,
  VariableDeclarationKind,
  InterfaceDeclaration,
} from "ts-morph";

// initName is name of the interface file below the root, ./src is considered the root
const Keys = (intName: string): string[] => {
  const project = new Project();
  const sourceFile = project.addSourceFileAtPath(`./src/${intName}.ts`);
  const node = sourceFile.getInterface(intName)!;
  const allKeys = node.getProperties().map((p) => p.getName());

  return allKeys;
};

export default Keys;

使用

import keys from "./keys";

const myKeys = keys("MyInterface") //ts file name without extension

console.log(myKeys)

其他回答

安全的变体

从具有安全编译时检查的接口创建键的数组或元组需要一点创造力。类型在运行时被擦除,对象类型(无序的,命名的)不能在不使用不支持的技术的情况下转换为元组类型(有序的,未命名的)。

与其他答案的比较

在给定IMyTable这样的引用对象类型的情况下,在重复或缺少元组项的情况下,这里提出的变体都考虑/触发编译错误。例如,声明一个数组类型为(keyof IMyTable)[]就不能捕获这些错误。

此外,它们不需要特定的库(最后一个变体使用ts-morph,我认为它是通用的编译器包装),发出与对象相反的元组类型(只有第一个解决方案创建数组)或宽数组类型(与这些答案相比),最后不需要类。

变体1:简单类型数组

// Record type ensures, we have no double or missing keys, values can be neglected
function createKeys(keyRecord: Record<keyof IMyTable, any>): (keyof IMyTable)[] {
  return Object.keys(keyRecord) as any
}

const keys = createKeys({ isDeleted: 1, createdAt: 1, title: 1, id: 1 })
// const keys: ("id" | "title" | "createdAt" | "isDeleted")[]

+最简单+-手动自动补全-数组,没有元组

操场上

如果您不喜欢创建记录,可以看看这个具有Set和断言类型的替代方法。


变体2:带有helper函数的元组

function createKeys<T extends readonly (keyof IMyTable)[] | [keyof IMyTable]>(
    t: T & CheckMissing<T, IMyTable> & CheckDuplicate<T>): T {
    return t
}

+ tuple +-手动自动补全+-更高级,更复杂的类型

操场上

解释

createKeys通过将函数参数类型与附加断言类型合并来进行编译时检查,这些断言类型会在不合适的输入时发出错误。(keyof IMyTable)[] | [keyof IMyTable]是一种“黑魔法”方式,从被调用方强制推断一个元组而不是一个数组。或者,你可以从调用方使用const断言/作为const。

CheckMissing检查,如果T错过了U的键:

type CheckMissing<T extends readonly any[], U extends Record<string, any>> = {
    [K in keyof U]: K extends T[number] ? never : K
}[keyof U] extends never ? T : T & "Error: missing keys"

type T1 = CheckMissing<["p1"], {p1:any, p2:any}> //["p1"] & "Error: missing keys"
type T2 = CheckMissing<["p1", "p2"], { p1: any, p2: any }> // ["p1", "p2"]

注意:T和“错误:缺少键”只是IDE错误。你也可以写成never。checkduplicate检查双元组项:

type CheckDuplicate<T extends readonly any[]> = {
    [P1 in keyof T]: "_flag_" extends
    { [P2 in keyof T]: P2 extends P1 ? never :
        T[P2] extends T[P1] ? "_flag_" : never }[keyof T] ?
    [T[P1], "Error: duplicate"] : T[P1]
}

type T3 = CheckDuplicate<[1, 2, 3]> // [1, 2, 3]
type T4 = CheckDuplicate<[1, 2, 1]> 
// [[1, "Error: duplicate"], 2, [1, "Error: duplicate"]]

注意:关于元组中唯一项检查的更多信息在这篇文章中。在TS 4.1中,我们还可以在错误字符串中命名缺失的键-看看这个Playground。


变体3:递归类型

在4.1版中,TypeScript正式支持条件递归类型,这里也可以使用它。然而,由于组合的复杂性,类型计算是昂贵的——超过5-6个项目的性能会大幅下降。为了完整起见,我列出了这个替代方案(Playground):

type Prepend<T, U extends any[]> = [T, ...U] // TS 4.0 variadic tuples

type Keys<T extends Record<string, any>> = Keys_<T, []>
type Keys_<T extends Record<string, any>, U extends PropertyKey[]> =
  {
    [P in keyof T]: {} extends Omit<T, P> ? [P] : Prepend<P, Keys_<Omit<T, P>, U>>
  }[keyof T]

const t1: Keys<IMyTable> = ["createdAt", "isDeleted", "id", "title"] // ✔

+ tuple +-手动自动补全+无辅助功能——性能


变体4:代码生成器/ TS编译器API

这里选择TS -morph,因为它是原始TS编译器API的简单包装器替代品。当然,也可以直接使用编译器API。让我们看看生成器代码:

// ./src/mybuildstep.ts
import {Project, VariableDeclarationKind, InterfaceDeclaration } from "ts-morph";

const project = new Project();
// source file with IMyTable interface
const sourceFile = project.addSourceFileAtPath("./src/IMyTable.ts"); 
// target file to write the keys string array to
const destFile = project.createSourceFile("./src/generated/IMyTable-keys.ts", "", {
  overwrite: true // overwrite if exists
}); 

function createKeys(node: InterfaceDeclaration) {
  const allKeys = node.getProperties().map(p => p.getName());
  destFile.addVariableStatement({
    declarationKind: VariableDeclarationKind.Const,
    declarations: [{
        name: "keys",
        initializer: writer =>
          writer.write(`${JSON.stringify(allKeys)} as const`)
    }]
  });
}

createKeys(sourceFile.getInterface("IMyTable")!);
destFile.saveSync(); // flush all changes and write to disk

在我们用tsc && node dist/mybuildstep.js编译并运行这个文件之后,一个文件./src/generated/IMyTable-keys。生成内容如下的Ts:

// ./src/generated/IMyTable-keys.ts
const keys = ["id","title","createdAt","isDeleted"] as const;

+自动生成解决方案+可扩展的多个属性+无辅助功能+元组-额外的构建步骤-需要熟悉编译器API

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

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"];

这是一个艰难的问题!谢谢大家的帮助。

我的需要是将接口的键作为字符串数组来简化mocha/chai脚本。不关心在应用程序中使用(还),所以不需要创建ts文件。感谢ford04的帮助,他上面的解决方案是一个巨大的帮助,它的工作完美,没有编译器黑客。下面是修改后的代码:

选项2:基于TS编译器API的代码生成器(TS -morph)

节点模块

npm install --save-dev ts-morph

keys.ts

注意:这里假设所有ts文件都位于./src的根目录下,并且没有子文件夹,请相应地调整

import {
  Project,
  VariableDeclarationKind,
  InterfaceDeclaration,
} from "ts-morph";

// initName is name of the interface file below the root, ./src is considered the root
const Keys = (intName: string): string[] => {
  const project = new Project();
  const sourceFile = project.addSourceFileAtPath(`./src/${intName}.ts`);
  const node = sourceFile.getInterface(intName)!;
  const allKeys = node.getProperties().map((p) => p.getName());

  return allKeys;
};

export default Keys;

使用

import keys from "./keys";

const myKeys = keys("MyInterface") //ts file name without extension

console.log(myKeys)

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

export class YourClass implements IMyTable {
    ...
}

then

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