TypeScript switch-case穷举检查不起作用?

时间:2017-06-20 13:51:26

标签: typescript union-types

const changeToInvalidations = (change: Change): Array<Invalidation> => {
  switch (change.resourceType) {
    case "brand":
      switch (change.type) {
        case "added":
          return [{ type: "page", value: "productListing" }]
        case "updated":
          return [{ type: "brand", value: change.resourceId }]
        case "removed":
          return [{ type: "brand", value: change.resourceId }]
      }
    case "product":
      switch (change.type) {
        case "added":
          return [{ type: "page", value: "productListing" }]
        case "updated":
          return [{ type: "product", value: change.resourceId }]
        case "removed":
          return [
            { type: "page", value: "productListing" }, // pagination reflow
            { type: "brand", value: change.resourceId },
          ]
      }
  }
}

Change类型的定义:

type Change = {
  type: "added" | "updated" | "removed"
  resourceId: number
  resourceType: "brand" | "product"
}

错误:

  

函数缺少结束return语句,返回类型不包括&#39; undefined&#39;

但是从阅读https://www.typescriptlang.org/docs/handbook/advanced-types.html

开始

看来我应该好好去。我做错了什么?

1 个答案:

答案 0 :(得分:0)

错误消息可能是指缺少default:的情况,其中没有定义return语句。如果resourceTypetype属性为undefined,则会切换为default个案。