I'm struggling to type a function with this behaviour :
given a object conf with an undefined number of keys, each key being an object with value and type properties, the function should return an object with the same properties and only value as value.
So to be clear, this is an example of function input:
{
foo: {value: 1, type: 'number'},
bar: {value: 'hello', type: 'string'}
}
and the corresponding output:
{
foo: 1,
bar: 'hello'
}
Here is what I've written so far:
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> }
That is obviously not correct since :
- T can only take one type at a time (the example above will throw an error on property
bar) - The return type has an undefined number of keys, instead of being all and only keys present in input object.
But I am a little lost here and don't really know where to look, nor if that's even possible.
f()to care about the input value properties having the right relationship between theirvalueandtypeproperties? If so, what strings cantypebe? It looks almost like the runtime output oftypeof valueexcept that there's no"array"primitive (it would beobjectat runtime).