安全变体
从具有安全编译时检查的接口创建一个数组或tuple 键需要一点创造力。类型在运行时被擦除,对象类型(无序、命名)无法转换为元组类型(有序、无名)without resorting to non-supported techniques。
与其他答案的比较
这里提出的变体都考虑/触发一个编译错误,以防重复或缺失的元组项给定一个引用对象类型,如IMyTable。例如声明(keyof IMyTable)[] 的数组类型无法捕获这些错误。
此外,它们不需要a specific library(最后一个变体使用ts-morph,我认为它是一个通用编译器包装器),发出一个元组类型as opposed to an object(只有第一个解决方案创建一个数组)或宽数组输入(比较theseanswers),最后输入don't need classes。
变体 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")[]
+最简单的+-手动自动完成-数组,没有元组
Playground
如果您不喜欢创建记录,请查看this alternative with Set and assertion types。
变体 2:带有辅助函数的元组
function createKeys<T extends readonly (keyof IMyTable)[] | [keyof IMyTable]>(
t: T & CheckMissing<T, IMyTable> & CheckDuplicate<T>): T {
return t
}
+ tuple +- 具有自动完成功能的手动 +- 更高级、更复杂的类型
Playground
说明
createKeys 会在编译时检查 by merging 函数参数类型以及其他断言类型,这些断言类型会针对不合适的输入发出错误。 (keyof IMyTable)[] | [keyof IMyTable] 是一个 "black magic" way,用于强制从被调用方推断元组而不是数组。或者,您可以在调用方使用const assertions / as 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 & "Error: missing keys" 仅用于漂亮的 IDE 错误。你也可以写never。 CheckDuplicates 检查双元组项:
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"]]
注意:有关元组中唯一项目检查的更多信息在 this post 中。使用TS 4.1,我们还可以在错误字符串中命名缺失的键——看看this Playground。
变体 3:递归类型
TypeScript 4.1 版本正式支持conditional recursive types,这里也可以使用。但是,由于组合复杂性,类型计算成本很高 - 超过 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,因为它是original TS compiler 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