What I'm looking for
In a key-value parent object, I have multiple objects with a property called namespaced
of type boolean
:
const obj1 = {
namespaced: true,
a() {}
} as const
const obj2 = {
namespaced: false,
b() {}
} as const
const parentObj = {
obj1,
obj2
} as const
I want to create a mapped type that only includes objects with namespaced
set to true
(and another one for false
). Can this be achieved?
My approach so far
interface ParentObj {
[name: string]: Obj
}
interface Obj {
namespaced: boolean
}
type FilterNamespaced<P extends ParentObj> = {
[O in keyof P]: P[O] extends { namespaced: true } ? P[O] : never
}
type FilterNotNamespaced<P extends ParentObj> = {
[O in keyof P]: P[O] extends { namespaced: false } ? P[O] : never
}
type F1 = FilterNamespaced<typeof parentObj>
type F2 = FilterNotNamespaced<typeof parentObj>
Although the code is working to some extent, I still end up with unwanted keys like obj2
in F1
and obj1
in F2
. I would like these keys to be excluded from the result.