【发布时间】:2020-01-08 13:30:16
【问题描述】:
我正在努力输入具有这种行为的函数:
给定一个对象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 一次只能采用一种类型(上面的示例将在属性
bar上抛出错误) - 返回类型具有未定义数量的键,而不是输入对象中存在的全部且唯一的键。
但我有点迷路了,不知道该去哪里看,也不知道这是否可能。
【问题讨论】:
-
您是否需要
f()来关心其value和type属性之间具有正确关系的输入值属性?如果是这样,type可以是什么字符串?它看起来几乎类似于typeof value的运行时输出,只是没有"array"原语(运行时为object)。
标签: typescript generics types typescript-typings typescript-generics