Home > Blockchain >  TypeScript Union Question (using two objects)
TypeScript Union Question (using two objects)

Time:01-05

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.

error message

Property 'name' does not exist on type 'B | A'. Property 'name' does not exist on type 'B'.

CodePudding user response:

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

  • Related