skip to Main Content

Giving following typescript code. how would you omit the email that is inside options and inside data?

interface SignUpObject {
  email:string, // not this one
  password: string,
  options: {
    emailRedirectTo: string,
    captchaToken?: string,
    data: {
      preferedLanguage: number
      name: string
      email: string // but this one!
      agreeTermsCheckbox: boolean
      whatJobYouHave: number
      birthday: string
      techYearsOfExpierence: string
      is_subscriber: boolean
      is_admin: boolean
      subscriber_expiration_timestamp: string | null
    }
  }
}

I already omit password:

interface UpdateUserData extends Omit<SignUpObject, 'password'> {
  password?: string
}

I try search online, reading the docs, looking in forums and more

2

Answers


  1. Overwrite options.data as you did for password field:

    interface UpdateUserData extends Omit<SignUpObject, 'password' | 'options'> {
      password?: string;
      options: Omit<SignUpObject['options'], 'data'>
      & {
        data: Omit<SignUpObject['options']['data'], 'email'>
      }
    }
    
    Login or Signup to reply.
  2. You could use a recursive generic type to filter a particular object path out:

    export type Leaves<T> = T extends object ? { [K in keyof T]:
        `${Exclude<K, symbol>}${Leaves<T[K]> extends never ? "" : `.${Leaves<T[K]>}`}`
    }[keyof T] : never
    
    type OmitPath<T, P extends Leaves<T>> = T extends object ? 
      P extends keyof T ? 
        { [K in Exclude<keyof T, P>]: T[K] } : 
          { [K in keyof T]: 
            P extends `${Exclude<K, symbol>}.${infer R extends Leaves<T[K]>}` ? 
            OmitPath<T[K], R> : T[K]}
    : never;
    
    type SignUp = OmitPath<SignUpObject, 'options.data.email'>
    

    Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search