Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript Union Question (using two objects)

interface A {
  profile: string;
  name: string;
  c: number;
  d: number;
}

interface B {
  title: string;
  profile: string;
  a: number;
  b: number;
}

function abFunc(obj: B | A) {
  return obj.name || obj.title
}

Like the interface above, there is data A or B. The above data also have overlapping properties.

How should we define the type in the function below?

‘A|B’ is used, so only duplicate properties are available.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error message

Property ‘name’ does not exist on type ‘B | A’.
Property ‘name’ does not exist on type ‘B’.

>Solution :

You would need to discriminate the union, for example with the operator in :

function abFunc(obj: B | A) {
  return 'name' in obj ? obj.name : obj.title
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading