Home > Mobile >  Union Types with interfaces, recognize only shared property
Union Types with interfaces, recognize only shared property

Time:06-17

I would like to use two interfaces as in a Union Types in TypeScript, but as you can see in the simple example below, I can not check to see what type the parameter is and I can just access the properties that the two interfaces share. Do you have any suggestions on what should I do?

simple example

CodePudding user response:

You'll need a discriminated unions.

interface Foo {
   id: string;
   name: string;
   type: "Foo";
}

interface Bar {
   id: string;
   phoneNumber: number;
   type: "Bar";
}

function baz(input: Foo | Bar) {
   if(input.type === "Bar") {
      input.phoneNumber 
   }
}

Playground

CodePudding user response:

input has the type Foo | Bar, which means, at this point, for TypeScript, it can be one of them, but can't tell further. So it only knows id, the shared property. You should have a type checking. I would do something like this:

Notice I'm using this this type propriety. Here a TypeScript Playground if you want to.

interface Foo{
  id:string;
  name:string;
  type:"Foo"

}

interface Bar{
  id:string;
  phoneNumber:string;
  type:"Bar"

}

function bas(input : Foo| Bar){
  if(input.type === "Bar"){
    input.phoneNumber
  }else{
    input.name
  }
}

CodePudding user response:

You should extend your interface from a basic interface with id like so:

interface IdAble {
  id: string;
}

interface Foo extends IdAble {
  name: string;
}

interface Bar extends IdAble {
  phoneNumber: number;
}
  • Related