Apakah mungkin menemukan item dalam array dengan tipe khusus?

type A = {
  x: number;
};

type B = {
  y: number;
};

type Mixed = A | B;

const list: Mixed[] = [{x:5}, {y:3}];

const a = list.find(item => 'x' in item);  // <-- how to make something like this work?

0
ThirstyForJava 12 Mei 2021, 04:02

1 menjawab

Jawaban Terbaik

Ini harus bekerja:

type A = {
    x: number;
  };
  
  type B = {
    y: number;
  };
  
  type Mixed = A | B;
  
  const list: Mixed[] = [{x:5}, {y:3}];
  
  const a = list.find(item => item.hasOwnProperty('x')) as A;
  
0
Aadmaa 12 Mei 2021, 01:16