z-pattern-matching / z

Pattern Matching for Javascript
https://z-pattern-matching.github.io/
Apache License 2.0
1.72k stars 50 forks source link

Type definitions? #69

Open EduardoAraujoB opened 3 years ago

EduardoAraujoB commented 3 years ago

So, I'm about to start using this lib in a project, but I figured out that there is no type declaration file for the project or a @types/z package

EduardoAraujoB commented 3 years ago

I also wrote a simple type definition in my project

//  T is the return type and U is the type of the parameter
declare module 'z' {
  type Matches = <T, U>(
    value: U,
  ) => (
    matcher: (value: U) => void,
    matcher?: (value: U) => void,
    matcher?: (value: U) => void,
    matcher?: (value: U) => void,
  ) => T;

  export const matches: Matches;
}

those types are obiviously wrong and there is some problems, one of them is that I need to keep repeating the optional matcher parameter in the type definition file when pattern matching have more matchers than the defined (4 in this case)

nythrox commented 2 years ago

This works for values

declare module 'z' {

  type Matcher<U, R> = (value: U) => R

  type Matches = <U>(value: U) => <M extends Matcher<U, any>[]>(
    ...matchers: M
  ) => M extends Matcher<infer _, infer R>[] ? R : never;

  const matches: Matches;

}