Home > Mobile >  Typescript object same structure but different types, how to union?
Typescript object same structure but different types, how to union?

Time:01-12

  export interface TEST {
   action: 'action1' | 'action2' | 'action3',
   params: User | BadUser
  }

  interface User {
   name: string | null,
   date: string | null,
   ...
  }

  interface BadUser {
   badName: string | null,
   badDate: string | null,
   ...
  }

How to acces someUser.params.name or someBadUser.params.badName correctly ?

CodePudding user response:

You may use the in operator to check if a field is present on the params:

function something(thing: TEST) {
    if ("name" in thing.params) {
        return thing.params.date;
    } else {
        return thing.params.badDate;
    }
}

Playground

CodePudding user response:

let test: TEST = {};

return test.params.name ?? test.params.badName;    
or
return test.params.date ?? test.params.badDate;
  • Related