Skip to content

More accurate types in guard clauses and handler functions #2

Description

@ygunayer

Handlers in case handles receive values as type any, but with some TypeScript magic we should be able to provide a much more accurate type information as a case is being build.

Consider the following example for what we're envisioning:

const dateRegex = /(\d{4})\-(\d{1,2})-(\d{1,2})/;

match('2018-02-29').case(
  [dateRegex, [y => y % 4 != 0, 2, 29], ([y, m, d]) => console.log(`Valid date string but invalid date ${y}-${m}-${d}`)],
  [dateRegex, ([y, m, d]) => console.log(`Valid date ${y}-${m}-${d}`)],
  [_, s => console.log(`Invalid date string: ${s}`)]
);

In such a case, we expect the guard and handler handles in the first two cases receive values of type RegExpMatchArray and not any or null|RegExpMatchArray because we're certain that if the regex doesn't match, execution wouldn't even proceed further in that case; whereas in the last case the handler should receive a value of type string because that's the type of the initial case.

Another similar use case is as follows, notice the use of ===:

match('42').case(
  [Number, x => x === 42, 'answer to life, the universe, and everything'],
  [Number, 'just an ordinary number'],
  [_, 'not even a number']
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions