[TypeScript] Find common props between two types, keyword Extract
For example we have two types, we want to find the shared props in both:
interface UserBase { email: string image: string | null username: string } interface UserProfile { id: string email: string image: string | null isAdmin: boolean username: string reviews: string[] }
We can use 'Extract'
type SharedUserKeys = Extract<keyof UserBase, keyof UserProfile> // 'email' | 'image' | 'username'
Convert our union string back into an object type with the shared properties and their corresponding value types.
'in' keyword, means loop over all the key in the union type.
type SharedUserData = { [K in SharedUserKeys]: UserProfile[K] } const user1: SharedUserData = { email: 'test@example.com', image: null, username: 'sampleuser', }