In the following case, is it possible to correctly infer the type of result correctly as boolean?
interface ActionWithPayload<T extends string, K> { type: T, payload: K }
function ofType<T extends ActionWithPayload<string, any>>(...param: T["type"][]): T extends ActionWithPayload<typeof param[number], infer U> ? U : never {
return null;
}
enum one {
foo = "foo",
bar = "bar"
}
type action = ActionWithPayload<one.foo, boolean> | ActionWithPayload<one.bar, string>;
var result = ofType<action>(one.foo); // type of result should be boolean
The problem is that
T["type"]whenTisactionwill beone.foo | one.barregardless of what parameters you pass. You need an extra generic parameter so the compiler will infer the literal type for the enum member you pass in:The disadvantage is that you have to explicitly specify the literal type
one.foosince you can't specify just one of the type parameters. As an alternative you could use a two function approach so you can specify the type parameter to the first function and let inference work for the second function: