typescript - 打字稿多泛型对象声明
问题描述
我正在努力键入具有这种行为的函数:给定一个conf
具有未定义数量的键的对象,每个键都是一个具有value
和type
属性的对象,该函数应该返回一个具有相同属性的对象,并且仅value
与value
.
所以要清楚,这是一个函数输入的例子:
{
foo: {value: 1, type: 'number'},
bar: {value: 'hello', type: 'string'}
}
和相应的输出:
{
foo: 1,
bar: 'hello'
}
这是我到目前为止所写的:
type TypeWithName<T extends string> =
T extends 'number' ? number :
T extends 'boolean' ? boolean :
T extends 'undefined' ? undefined :
T extends 'array' ? string[] :
string
declare function f<T extends string>(conf: {
[key: string]: { default: TypeWithName<T>; type: T }
}): { [P in keyof typeof conf]: TypeWithName<T> }
这显然是不正确的,因为:
- T一次只能采用一种类型(上面的示例将在 property 上抛出错误
bar
) - 返回类型具有未定义数量的键,而不是输入对象中存在的所有且唯一的键。
但是我在这里有点迷路,真的不知道该去哪里看,也不知道这是否可能。
解决方案
您可以尝试以下方法:
const conf = {
foo: { value: 1, type: "number" },
bar: { value: "hello", type: "string" }
};
type Input = {
[key: string]: { value: any; type: string };
};
type Output<U extends Input> = { [Key in keyof U]: U[Key]["value"] };
function f<T extends Input>(input: T): Output<T> {
// Details...
}
const returned = f(conf);
returned.foo // number
returned.bar // string