zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[TypeScript] Find common props between two types, keyword Extract

typescript Find two between Common types keyword Props
2023-09-14 09:00:45 时间

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',
}