Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(exhaustive): Add support for passing a fallback function #253

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

gvergnaud
Copy link
Owner

@gvergnaud gvergnaud commented May 23, 2024

Solves #144 #218 and replaces #38 #219

Docs

By default, .exhaustive() will throw an error if the input value wasn't handled by any .with(...) clause. This should only happen if your types are incorrect.

It is possible to pass your own handler function as a parameter to decide what should happen if an unexpected value has been received. You can for example throw your own custom error:

match(...)
  .with(...)
  .exhaustive((unexpected: unknown) => {
    throw MyCustomError(unexpected);
  })

Or log an error and return a default value:

match<string, number>(...)
  .with(P.string, (str) => str.length)
  .exhaustive((notAString: unknown) => {
    console.log(`received an unexpected value: ${notAString}`);
    return 0;
  })

@gvergnaud gvergnaud mentioned this pull request May 23, 2024
@danielsantiago
Copy link

Is there anything we can do to make this solution implemented?

@gvergnaud gvergnaud force-pushed the gvergnaud/add-exhaustive-fallback-support branch from 1585b35 to 12c067e Compare December 15, 2024 02:53
@gvergnaud gvergnaud force-pushed the gvergnaud/add-exhaustive-fallback-support branch from 12c067e to 5841013 Compare December 15, 2024 02:55
@Fasaloft
Copy link

Hello @gvergnaud, I have a question: What can I do to include this awesome feature in the release? It would really help me write clean and safe pattern matching even in production.

@gvergnaud
Copy link
Owner Author

I think I'll include it in the next release. I'll try to ship it in the next few weeks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants