-
-
Notifications
You must be signed in to change notification settings - Fork 59
Inference from pattern matching #344
Comments
type for also this snippet fails to type check and produces this |
It says
That's the point if this issue. It's not clear to me if you're debating or elaborating? 🙂 Inference from usage seems to be about "what could the developer possibly mean" - and in this particular case, it seems less likely you'd want |
elaborating your issue seems to be about inferring type of for example if
so why do you have default case if only
that function can handle any object as so constraining |
Because JavaScript? Type-checking is compile-time, so somebody will always be able to pass anything.
But there's no such thing as an exhaustive switch/case in JS - so no matter what I do, handling Reducer patterns like these are super common in JS now - is there some way we can handle them? |
Hey, @mindplay-dk. function update(state, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
// case "VALID_BUT_NOT_HANDLED_ACTION":
default:
return state;
}
}
let nextState = update(0, { type: "VALID_BUT_NOT_HANDLED_ACTION" }); // should be a type error here? Seems like, if a developer will have same logic for some action and |
Yeah, How about this then? function update(state, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
throw new Error(`unsupported action: ${action.type}`);
}
} Or just this: function update(state, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
}
throw new Error(`unsupported action: ${action.type}`);
} Any |
@mindplay-dk that sounds like a good idea and would imply that this code function concat(a, b) {
if (typeof a !== "string") throw new TypeError("a must be a string!");
if (typeof b !== "string") throw new TypeError("b must be a string!");
return a + b;
} will produce this interface
instead of this one
which would be very good for inferring types of js code instead of using poorly implemented |
Would it possible (and would it make sense) to add inference for pattern matching?
For example:
Here, it's clear from reading the code that
action.type
has a defined set of expected values.Hegel does infer from usage that
action
must have atype
property.But it does not infer that the
type
is a string - although it's clear to a person familiar with pattern matching that, not only is a string property expected, but there is also an expected set of constant string types.I'm sure this is non-trivial, but I'm wondering if it's even possible and whether it would make sense? 🙂
The text was updated successfully, but these errors were encountered: