Is there a way to consolidate multiple interfaces/types in Typescript by merging them? The resulting interface should have all shared properties as mandatory and all unique properties as optional. Here is an example:
interface ShopUser {
userId: string
boughtItems: string[]
}
interface BlogUser {
userId:string
viewedBlogs: string[]
}
interface AppUser {
userId: string
appSessions: string[]
}
The desired outcome would resemble the following structure:
interface DBUser {
userId: string // mandatory, present in all child interfaces
boughtItems?:string[] // now optional
viewedBlogs?:string[] // now optional
appSessions?:string[] // now optional
}
I have attempted various methods such as:
type DBUser = ShopUser | BlogUser | AppUser // only userId is accessible. Other properties remain unknown
type DBUser = ShopUser & BlogUser & AppUser // results in all properties being mandatory...
Utilizing something like
Omit<ShopUser, "boughtItems">
followed by redefining does not seem very elegant, especially given the complexity of our interfaces. It ends up being messy and lacks reusability.