I have an interface which acts as a parent of multiple child interfaces. For example:
interface ParentProps {
family?: ChildA & ChildB
}
What I would like to do, ideally, is in certain situations exclude either ChildA
or ChildB
interfaces from the family
prop.
I have tried some ideas but with errors.
interface FamTree extends Exclude<ParentProps['family'], ChildA> {}
An interface can only extend an object type or intersection of object types with statically known members
When I try doing this as a type instead of an interface, I don't get any errors, but I also don't get the correct types, either.
type FamTree = Exclude<ParentProps['family'], ChildA>;
This results in FamTree
having a type of never
though. Not sure how best to approach this.
The end result I am looking to achieve is:
type FamTree = {
family?: ChildB
}
To solve this, you can Exclude
undefined from ParentProps['family']
and afterwards Omit
all keys of ChildA
from the resulting type.
type FamTree = Omit<Exclude<ParentProps['family'], undefined>, keyof ChildA>
If you want to keep shared properties, you have to Exclude
all the keys from A
which B
also has.
type FamTree = Omit<
Exclude<ParentProps['family'], undefined>, Exclude<keyof ChildA, keyof ChildB>
>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.