Skip to content

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

Merged
gvergnaud merged 6 commits intomainfrom
gvergnaud/add-exhaustive-fallback-support
Mar 28, 2025
Merged

feat(exhaustive): Add support for passing a fallback function#253
gvergnaud merged 6 commits intomainfrom
gvergnaud/add-exhaustive-fallback-support

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 2 times, most recently 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

@gvergnaud gvergnaud force-pushed the gvergnaud/add-exhaustive-fallback-support branch from 8151846 to 1f8e197 Compare March 28, 2025 20:03
@gvergnaud gvergnaud merged commit 60af216 into main Mar 28, 2025
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