DEV Community

Discussion on: The Power of Union and Type Guard in TypeScript 🤯

Collapse
 
arihantverma profile image
Arihant Verma • Edited

If we have

interface A {
    name: string;
    id: number;
}

interface B {
  uni: string;
  age: number;
}

type ArrType = Array<A | B>

declare var arr;
let arr: ArrType;

arr.map(item => {
     // need to detect if item is of type A or B
})
Enter fullscreen mode Exit fullscreen mode

How can we do this…?

Collapse
 
crusader4christ profile image
Herman Klushin • Edited
function isA(v): v is A {
  return "name" in v && "id" in v;
}

function isB(v): v is B {
  return "uni" in v && "age" in v;
}
arr.map(item => {
  if(isA(item)) {
    console.log(item.id, item.name);
  }
})
Enter fullscreen mode Exit fullscreen mode