DEV Community

Discussion on: Matching your way to consistent states

Collapse
 
marcinkoziej profile image
Marcin Kozey

Thanks for the article. Could You explain what is the benefit of using match() function in comparison to using TypeScript switch statement? AFAIK it also performs the exhaustiveness check

Collapse
 
gillchristian profile image
Christian Gill • Edited

To me match feels more declarative, we aren't checking the internal representation of the RemoteData value, only providing handlers for all the cases. And since it is function call, it is an expression, wheres switch is a statement.

Eg. going from this to using switch would require quite some boilerplate code.

const MyComponent = ({ data }) => (
  <div className="my-component-styles">
    {match({ ... })(data)}
  </div>
)
Enter fullscreen mode Exit fullscreen mode

It's true that TypeScript can do exhaustiveness check on the switch statement. But that requires either to add a default case with a never assertion, or to be in a context where we have to return something in all the branches.

Eg. in a case like this, the switch would produce no error but the match would.

switch(someRemoteData.status) {
  case 'not_asked':
    doSomethingWhenNotAsked()
    break
  case 'loading':
    doSomethingWhenLoading()
    break
}

match({
  not_asked: () => doSomethingWhenNotAsked(),
  loading: () => doSomethingWhenLoading(),
})(someRemoteData)
Enter fullscreen mode Exit fullscreen mode

Ultimately, I think it's a matter of personal preference, based on what are the priorities and what the team feels more comfortable with.