If you have a type like Example
that you want to convert into this structure, you can do it like this:
type OuterObject<T extends object> = {
[K in keyof T]: InnerObject<K>
}
The idea is that we are mapping InnerObject<K>
over each K
in keyof T
.
Importantly, the difference between this and what you wrote is that you were operating on the whole union keyof T
and not each element in the union. It’s the difference between {[X in Y]: F<X>}
, which evaluates to a possibly different type for each property, and {[X in Y]: F<Y>}
which does not.
This produces the behavior you’re looking for:
const obj: OuterObject<Example> = {
foo: {
name: 'whatever',
ref: 'foo',
},
bar: {
name: 'baz',
ref: 'foo' // error!
}
}
Does that work for you?
CLICK HERE to find out more related problems solutions.