Home > other >  Union operator in interface and TypeScript error 2339
Union operator in interface and TypeScript error 2339

Time:11-11

Is it possible to combine inside interface other interfaces like:

interface IList {
  list: IData[] | IData2[];
  flow: SelectedTab;
}

IData and IData2 are with different params. So it should (correct me if I'm wrong) take params from IData or IData2. Conditionally I'm passing an array with objects for IData or IData2.

But TypeScript says:

Property 'language' does not exist on type 'IDataLanguageCountry | IDataCurrency'. Property 'language' does not exist on type 'IDataCurrency'.ts(2339)

Code to reproduce:

interface IData { data1: string }
interface IData2 { data2: string }
const list: IData[] | IData2[] = []

for (const item of list) {
  item.data1 // error
}

So it means I can't do this or am I doing something wrong? Any ideas how to "fix" it?

CodePudding user response:

Before using either data1 or data2 you need to prove to the TS compiler which one of either of your types you really have:

interface IData { data1: string }
interface IData2 { data2: string }
const list: IData[] | IData2[] = []

for (const item of list) {
  if ("data1" in item)
    item.data1
  // ^? IData
  if ("data2" in item)
    item.data2
  // ^? IData2
}

tsplayground

See handbook: https://www.typescriptlang.org/docs/handbook/2/narrowing.html

  • Related