Skip to content

Switch sometimes (non-deterministically?) results in redundant conditional block #7465

Closed
@mediremi

Description

@mediremi

ReScript version: v12.0.0-alpha.13

The following code (playground link)

type actionType1 =
  | WithoutPayload1
  | WithPayload1({x: int})

type actionType2 =
  | WithoutPayload2
  | WithPayload2({y: int})
  | WithPayload3({y: int})

type actionType3 =
  | WithPayload4({x: int})
  | WithPayload5({y: int})
  | WithPayload6({x: int})
  | WithPayload7({y: int})
  | WithPayload8({x: int})

type action =
  | ...actionType1
  | ...actionType2
  | ...actionType3

let f = (action: action) => {
  switch action {
  | ...actionType3 => Console.log("hello")
  | _ => ()
  }
  42
}

sometimes gets compiled to

function f(action) {
  if (typeof action !== "object") {
    action === "WithoutPayload1";
  } else {
    switch (action.TAG) {
      case "WithPayload1" :
      case "WithPayload2" :
      case "WithPayload3" :
        break;
      default:
        console.log("hello");
    }
  }
  return 42;
}

I say 'sometimes' as by rerunning the compiler you can get the correct output of

function f(action) {
  if (typeof action === "object") {
    switch (action.TAG) {
      case "WithPayload4" :
      case "WithPayload5" :
      case "WithPayload6" :
      case "WithPayload7" :
      case "WithPayload8" :
        console.log("hello");
        break;
    }
  }
  return 42;
}

See this video:

Kooha-2025-05-12-19-47-57.webm

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions