使用区分联合类型时的TypeScript错误

时间:2019-07-08 18:20:15

标签: typescript

我正在尝试在TypeScript中使用区分联合类型,但出现以下错误:

Type '{ data: Aaaa | Bbbb; type: "aaaa" | "bbbb"; }' is not assignable to type 'EventData'.
  Type '{ data: Aaaa | Bbbb; type: "aaaa" | "bbbb"; }' is not assignable to type '{ type: "bbbb"; data: Bbbb; }'.
    Types of property 'type' are incompatible.
      Type '"aaaa" | "bbbb"' is not assignable to type '"bbbb"'.
        Type '"aaaa"' is not assignable to type '"bbbb"'.

使用以下代码:

export type Aaaa = {
    aPropForA: string
}

export type Bbbb = {
    somePropsB: number
}

export type EventData =
  | { type: 'aaaa'; data: Aaaa }
  | { type: 'bbbb'; data: Bbbb }

// simulate getting the data for brevity
declare const data: EventData['data'];
declare const type: EventData['type'];

export const getEventData = (): EventData => {
  return { // why is there an error?
    data,
    type,
  }
}

live

问题的根源是什么?如何在不进行类型转换的情况下进行修复?

1 个答案:

答案 0 :(得分:1)

这是一个错误,其原因是无法保证datatype的组合是正确的。在此代码中,分配是有效的,并且会导致错误的联合:

const data: EventData['data'] = { aPropForA: ""};
const type: EventData['type'] = "bbbb"

export const getEventData = (): EventData => {
  return { // why is there an error?
    data,
    type,
  }
}

在没有类型断言的情况下解决错误的唯一方法是进行必需的检查:

declare const data: EventData['data'];
declare const type: EventData['type'];

export const getEventData = (): EventData => {
  if(type === 'aaaa' && 'aPropForA' in data) {
    return { data, type,}
  } else if(type === 'bbbb' && 'somePropsB' in data) { 
    return { data, type,}
  }
  throw new Error("Invalid combination")
}