Skip to content

Commit

Permalink
make match infer its return type
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike96Angelo committed Feb 25, 2023
1 parent 6d1d285 commit 5a6c73b
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 13 deletions.
2 changes: 1 addition & 1 deletion example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const handleA = (abc: ABC) => {
}
console.log(
abc,
abc.match<string | number | boolean>({
abc.match({
A(a) {
return `A: ${a}`;
},
Expand Down
4 changes: 2 additions & 2 deletions optional-pair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ class OptionalPair<
});
}

both(): Optional<[first: A, second: B]> {
both(): Optional<Readonly<[first: A, second: B]>> {
return this.match({
Both(first, second) {
return toOptional([first, second]);
return toOptional([first, second] as const);
},
_() {
return None;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "variant-match",
"version": "2.0.3",
"version": "2.0.4",
"description": "Brings variant match pattern to TypeScript.",
"main": "mod.js",
"scripts": {
Expand Down
4 changes: 2 additions & 2 deletions result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,10 @@ class Result<
): Result<T, E> {
return this.match({
Ok(value) {
return filter(value) ? Ok(value) : Err(error());
return filter(value) ? Ok<T, E>(value) : Err<T, E>(error());
},
Err() {
return Err(error());
return Err<T, E>(error());
},
});
}
Expand Down
15 changes: 8 additions & 7 deletions variant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ type Matcher<V, R> = UnionToIntersection<
V extends Variant<infer K, any> ? Record<K, VariantBranch<V, R>> : never
>;

type MatcherReturn<M> = M extends Matcher<any, infer R> ? R : never;

const assertVariant = (v: any) => {
const hasType = typeof v?.kind === "string";
const hasValues = Array.isArray(v?.values);
Expand Down Expand Up @@ -69,13 +71,12 @@ abstract class VariantTypeClass<V extends Variant<any, any[]>> {
* all branches independently.
* @returns The result of the named branch or catchAll that was executed.
*/
match<R>(matcher: Exact<Matcher<V, R>, V["kind"]>): R;
match<R>(
matcher: Exact<
Partial<Matcher<V, R>> & Record<"_", Func<[this], R>>,
V["kind"] | "_"
>
): R;
match<M extends Matcher<V, any>>(
matcher: Exact<M, V["kind"]>
): MatcherReturn<M>;
match<M extends Partial<Matcher<V, any>>, R>(
matcher: Exact<M & Record<"_", Func<[this], R>>, V["kind"] | "_">
): R | MatcherReturn<M>;
match(matcher: any) {
const func = matcher[this.variant.kind] ?? matcher._;

Expand Down

0 comments on commit 5a6c73b

Please sign in to comment.