Skip to content

Support destructuring/pattern matching of record rest elements #8311

@tsnobip

Description

@tsnobip

Today, we support pattern matching of variant subtypes:

let greetAnimal = (animal: animals) => {
  switch animal {
  | ...pets as pet => greetPet(pet)
  | ...fish as fish => greetFish(fish)
  }
}

The goal of this issue is to design a way to pattern match on the rest elements of a record:

module PackageManagerConfig = {
  type t = {
    packageManagerName?: string,
    runtimeVersion?: string,
  }
}

module StyleConfig = {
  type t = {
    styleName?: string,
    theme?: string,
  }
}

module Config = {
  type t = {
    ...PackageManagerConfig.t,
    ...StyleConfig.t,
  }
}

let config = {Config.packageManagerName: "yarn", theme: "dark"}
let { ?Config.packageManagerName, ?runtimeVersion, ...StyleConfig.t as rest } = config

This would create a value rest of type StyleConfig.t.

This would allow to write in rescript a common pattern in JS/TS in react:

function MyComponent({ className, children, ...props }) {
  return (
    <div className={`w-full ${className}`} ...props >
     {children}
    </div>);
}

Today, this requires props drilling which has two drawbacks:

  • it can be cumbersome when you have many props
  • it changes unprovided props into undefined, which changes the behavior of props spreading when it's not the first argument of the component (undefined props erased overridden props while absent props do nothing).

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