我需要(如果可能)在TypeScrip中映射类型,其中我有一个由{ readonly name: string, readonly type: 'string' | 'number' }
个对象组成的元组,我想将其映射到一个类型,其中name
作为键,它们对应的type
(映射到实际类型)作为它们的类型.
例如,对于输入
const input = [
{ name: "foo", type: "string" },
{ name: "bar", type: "number" }
] as const
我需要一个像这样的类型:
type ExpectedOutput = {
foo: string,
bar: number
}
所以我正在搜索一个类型映射X
,使X<typeof input>
与ExpectedOutput
匹配.
映射type
非常简单明了:
type Type = "string" | "number";
type MapType<T extends Type> = T extends "string"
? string
: number
这样,映射单个元组条目就很容易了(并且工作正常):
type X_1<T extends { readonly name: string; readonly type: Type }> = {
[K in T["name"]]: MapType<T["type"]>;
};
const example: X_1<{ name: "age"; type: "number" }> = {
age: 42
}; // correct
const example2: X_1<{ name: "age"; type: "number" }> = {
age: "42"
}; // type error
只有当我try 拥有一组值时,我才会遇到问题:
type X<T extends readonly { readonly name: string; readonly type: Type }[]> = {
[K in T[number]["name"]]: MapType<T[number]["type"]>;
};
const tuple = [{ name: "age", type: "number" }, { name: "name", type: "string" }] as const;
const example3: X<typeof tuple> = {
age: 42,
name: "John"
}; // correct
const example4: X<typeof tuple> = {
age: "42",
name: "John"
}; // should have a type error, but doesn't
无论我try 做什么(我已经try 了几十种变体),这些属性的计算结果总是为any of the tuple's types(在本例中为string | number
),这是合理的,因为[number]
返回所有可能选项的并集.
我已经很久没有用打字字体做过深度"黑魔法"了,所以我甚至不太确定这是否可能.
提前感谢您的帮助/指点.
PS:这个问题(为简单起见我略go 了)的背景是,我正在构建一个库,该库在给定一组特定参数的情况下,应该构建一个zod
模式,该模式在验证后可以解析为正确的类型.