Assuming we have some definitions like this:
interface BoxType<T> { box: T }
interface FooType { foo: string }
interface BarType { bar: string }
declare function BoxType<T>(): BoxType<T>;
we can give the convert()
function the following call signature:
declare function convert<T extends object>(
input: { [K in keyof T]: BoxType<T[K]> }
): BoxType<{ [K in keyof T]-?: { name: K, value: T[K] } }[keyof T]>;
which I think behaves the way you want:
const result = convert({
foo: BoxType<FooType>(),
bar: BoxType<BarType>()
})
/*
const result: BoxType<{
name: "foo";
value: FooType;
} | {
name: "bar";
value: BarType;
}>
*/
The convert()
function is generic in T
, an object type never directly used as either the input or output, but looks like the type of input
with "unboxed" properties. We can define the input
type in terms of T
as a straightforward mapped type. {[K in keyof T]: BoxType<T[K]> }
, where we "box" each property. Since the type of input
maps over keyof T
, this is considered a "homomorphic" mapped type and the compiler can infer T
from input
. So far this is the same as what you have.
For the return type of the function, we want to take each property key K
in keyof T
and produce the union of { name: K, value: T[K] }
. In your code you took the union first before mapping. But the type {name: keyof T, value: T[keyof T]}
allows all sorts of undesirable values where name
comes from one key and value
from another. To keep them separate, we need to iterate over each key K
in keyof T
, and one easy way to do that is with another mapped type like {[K in keyof T]: {name: K, value: T[K]}}
.
Of course this type looks like {foo: {name: "foo", value: FooType}, bar: {name: "bar", value: BarType}}
... the property value types are what we want to get the union of and we don't want keys at all. Luckily here we can just index into it with keyof T
to produce the union of property value types. Hence {[K in keyof T]: {name: K, value: T[K]}}[keyof T]
.
And finally we wrap that in BoxType
: BoxType<{ [K in keyof T]: { name: K, value: T[K] }}[keyof T]>
. All done! Wait, oops, the only difference between that and the above output type is that we modify the properties of the mapped type by making sure they are not optional: BoxType<{ [K in keyof T]-?: { name: K, value: T[K] } }[keyof T]>
This prevents pesky undefined
values from creeping in if your input type T
happens to have optional properties. And now we're done.
Playground link to code
BoxType
? Is it a type or a function? What isMyType
? Is the property namedname
ortype
? Please consider making this code a minimal reproducible example suitable for dropping into a standalone IDE, preferably something you yourself have tested to make sure that you are asking what you intend to ask.MyType
was meant to beBoxType
, sorry for confusion. i am interested to see your explanation. thanks again