Closed thawankeane closed 1 year ago
For clarity: You don't want the handler's input narrowed to the return type of the predicate, you want the predicate to act as a type guard.
The main issue is knowing whether the predicate function even is a type guard. The only sensible solution is to explicitly annotate it.
Then it's a matter of typing .when()
to make use of that, if possible.
For clarity: You don't want the handler's input narrowed to the return type of the predicate, you want the predicate to act as a type guard.
Yeah, you're right
The main issue is knowing whether the predicate function even is a type guard. The only sensible solution is to explicitly annotate it.
As I'm using classes based typings, I ended up using .with
in combination with P.instanceOf
, but in a functional approach explicitly annotate would be a solution, could you please share some examples of how these annotations would be?
Taking your example:
match(unknownAnimal)
.when(
(animal): animal is Fish => animal.isFish(),
(fish) => {
fish.swim()
}
)
But I'm not sure if TS Pattern uses that to narrow the handler input.
But I'm not sure if TS Pattern uses that to narrow the handler input.
Yeah, it does. Thank you @darrylnoakes
When working with type predicates, the function
.when()
will always accept an type(value: TInput) => TOutput
as argument, but it will be very helpful (if possible) to infer thevalue
as the return type ofpredicate
argument, let me show some examples:Imagine that will have the following classes
Now, you want to use
ts-pattern
to exaustive check anAnimal
Describe the solution you'd like I would like if the second argument (
.when
callback) was typed as the return type of the first argument if possibleMaybe I might be missing something, so feel free to correct me if I'm doing something wrong
Describe alternatives you've considered I tried to explicit type the callback, but typescript doesn't allow to convert our input to the inferred type guard
Example: