我有一个类似这样的对象数组:
const options = [
{ name: "diameter", type: "number", value: 10, min: 0, max: 10 },
{ name: "height", type: "number", value: 2, min: 0, max: 8 },
{ name: "thickness", type: "number", value: 2, min: 0, max: 8 },
{ name: "text", type: "string", value: "Hello World" },
];
我想动态获取类型,所以有这样的东西;
type OptionsType = {
diameter: { value: number; min: number; max: number };
height: { value: number; min: number; max: number };
thickness: { value: number; min: number; max: number };
text: { value: string };
};
我尝试四处寻找,询问chatGPT / perplexity和supermaven,但没有找到解决方案。
关闭人工智能的解决方案尝试是这样的:
// Helper type to determine the correct parameter type based on 'type' property
type ParamType<T extends { type: string }> = T["type"] extends "number"
? { value: number; min: number; max: number }
: { value: string };
// Mapped type to transform the options array into the desired type definition
type OptionsParams<T extends readonly { name: string; type: string }[]> = {
[K in T[number] as K["name"]]: ParamType<Extract<T[number], { name: K }>>;
};
// Generate the type dynamically
type optionsParams = OptionsParams<typeof options>;
但是这个 optionsParams 的返回类型是:
type optionsParams = {
[x: string]: {
value: number;
min: number;
max: number;
};
}
所以它仅适用于(某种)数字值。
有什么建议如何解决这个问题,以及如何从 TypeScript 中给定的对象数组动态生成/映射类型吗?
如果你可以将
name
断言为 const,那么这将有效:
它从记录值类型中省略了
name
和type
,但关键是name
的const断言。
const options = [
{ name: "diameter" as const, type: "number", value: 10, min: 0, max: 10 },
{ name: "height" as const, type: "number", value: 2, min: 0, max: 8 },
{ name: "thickness" as const, type: "number", value: 2, min: 0, max: 8 },
{ name: "text" as const, type: "string", value: "Hello World" },
];
// Mapped type to transform the options array into the desired type definition
type OptionsParams<T extends readonly { name: string; type: string }[]> = Partial<{
[K in T[number] as K["name"]]: Omit<K, "name" | "type">;
}>;
// Generate the type dynamically
type optionsParams = OptionsParams<typeof options>;