Jason Kuhrt
Jason Kuhrt

Reputation: 840

TypeScript switch-case exhaustivity checking not working?

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 },
          ]
      }
  }
}

Definition of Change type:

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

Error:

Function lacks ending return statement and return type does not include 'undefined'

But from reading this https://www.typescriptlang.org/docs/handbook/advanced-types.html

It seems I should be good to go. What a I doing wrong?

Upvotes: 2

Views: 831

Answers (1)

Raven
Raven

Reputation: 1523

The error message is probably referring to the missing default: case where no return statement is defined. If the resourceType or type property is undefined it will switch to the default case.

Upvotes: 1

Related Questions