Is there anyway to do nested Pick types in Typescript

Similar to Colins answer, but coming at it from the opposite direction. If you have an existing interface/type you need to pick apart you can use indexes:


// Existing type
type Tenant = {
    id:string;
    description:string;
    name:string;
    approvedUsers: Array<{
      id:string;
      alias:string;
    }>
}

// Pick it apart
type TenantManagePageQueryTenant = 
  Pick<Tenant, 'id' | 'description' | 'name'> & {
    approvedUsers: Array<Pick<Tenant['approvedUsers'][0], 'id' | 'alias'>>
  }

Alternative 1 – Extracted types

As noted in the comments, this can be slightly cleaner:

type TenantSubset = Pick<Tenant, 'id' | 'description' | 'name'>
type ApprovedUserSubset = Pick<Tenant['approvedUsers'][number], 'id' | 'alias'>

type TenantManagePageQueryTenant = TenantSubset & { approvedUsers: Array<ApprovedUserSubset> }

Alternative 2 – Pick-less pick

This version, while a little more repetitive, is (subjectively) easier to read:

type TenantManagePageQueryTenant = { 
  id: Tenant['id'],
  description: Tenant['description'],
  name: Tenant['name'],
  approvedUsers: Array<{
    id: Tenant['approvedUsers'][number]['id'],
    alias: Tenant['approvedUsers'][number]['alias'],
  }> 
}

Playground

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)