Skip to content

Commit

Permalink
matcher: simplify function protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
gvergnaud committed May 8, 2023
1 parent 4b267c4 commit 2b16069
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 21 deletions.
6 changes: 2 additions & 4 deletions src/types/InvertPattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,7 @@ type InvertPatternInternal<p, input> = 0 extends 1 & p
and: ReduceIntersection<Extract<subpattern, readonly any[]>, input>;
or: ReduceUnion<Extract<subpattern, readonly any[]>, input>;
default: [subpattern] extends [never] ? input : subpattern;
custom: Override<
narrowFn extends Fn ? Apply<narrowFn, [input, subpattern]> : never
>;
custom: Override<narrowFn extends Fn ? Apply<narrowFn, input> : never>;
}[matcherType]
: p extends Primitives
? p
Expand Down Expand Up @@ -344,7 +342,7 @@ type InvertPatternForExcludeInternal<p, i, empty = never> =
>;
default: excluded;
custom: excluded extends infer narrowFn extends Fn
? Apply<narrowFn, [i, subpattern]>
? Apply<narrowFn, i>
: never;
}[matcherType]
: p extends readonly any[]
Expand Down
18 changes: 5 additions & 13 deletions src/types/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,18 +278,10 @@ export type GetKey<O, K> = O extends any
: never;

export interface Fn {
[rawArgs]: unknown;
args: this[rawArgs] extends infer args extends unknown[] ? args : never;
arg0: this[rawArgs] extends [infer arg, ...any] ? arg : never;
arg1: this[rawArgs] extends [any, infer arg, ...any] ? arg : never;
arg2: this[rawArgs] extends [any, any, infer arg, ...any] ? arg : never;
arg3: this[rawArgs] extends [any, any, any, infer arg, ...any] ? arg : never;
return: unknown;
input: unknown;
output: unknown;
}

export type Apply<fn extends Fn, args extends unknown[]> = (fn & {
[rawArgs]: args;
})['return'];

declare const rawArgs: unique symbol;
type rawArgs = typeof rawArgs;
export type Apply<fn extends Fn, input> = (fn & {
input: input;
})['output'];
8 changes: 4 additions & 4 deletions tests/matcher-protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ describe('matcher protocol', () => {
type SomeValue<T> = T extends Some<infer V> ? V : never;

interface SomeNarrowFn<p extends P.Pattern<unknown> = never> extends Fn {
return: [p] extends [never]
? Some<SomeValue<this['arg0']>>
: Some<P.narrow<SomeValue<this['arg0']>, p>>;
output: [p] extends [never]
? Some<SomeValue<this['input']>>
: Some<P.narrow<SomeValue<this['input']>, p>>;
}

class Some<const T> {
Expand Down Expand Up @@ -36,7 +36,7 @@ describe('matcher protocol', () => {
}
}
interface NoneNarrowFn extends Fn {
return: None;
output: None;
}
class None {
coucou: number;
Expand Down

0 comments on commit 2b16069

Please sign in to comment.