I am currently working on developing a simple type that would require a nested object key to reference the outer level.
For better understanding, let's take an example:
const obj = {
foo: {
name: 'bar',
ref: 'foo' // < this should reference the key of the parent
}
}
In a static object type, this wouldn't be a problem as we only need to check for 'foo'
, but I am aiming to make it dynamic with generic type arguments.
I attempted the following:
type InnerObject<K> = {
name: string,
ref: K,
}
type OuterObject<T, K extends keyof T> = {
[key in K]: InnerObject<K>
}
This almost works fine, enforcing type checking on the union of current keys:
https://i.sstatic.net/bZBxR.png
The problem is that it also permits passing the other object key to the ref
property when it shouldn't.
https://i.sstatic.net/zqMzm.png
I've been contemplating creating a third type generic and using the Exclude
utility type, like so:
type InnerObject<T, K extends keyof T, CurrentKey> = {
name: string,
ref: Exclude<CurrentKey, K>
}
However, the issue lies in figuring out how to pass the current key of the indexed object without explicitly writing a reducer/map function on the outer object.
Is this achievable or simply not possible in typescript?
Here is a link to the playground relevant to this topic.