'Function Argument Type Grouping
Problem
I have these two interfaces:
interface A {
type: "a";
aSpecificProp: number;
}
interface B {
type: "b";
bSpecificProp: boolean;
}
I am trying to implement a function myFunc that accepts two parameters x, y that must typed together (i.e. both of type A or both of type B).
Attempt #1:
myFunc = (x: A | B, y: A | B) => {};
The problem with this is that x and y do not necessarily have to both be of type A or of type B.
Attempt 2
type AorB = { x: A, y: A } | { x: B, y: B };
myFunc = (...{a, b}: AorB) => {};
If I use a typeguard inside myFunc to narrow down x to type A for example, y unfortunately will not also narrow down to type A.
Attempt 3 - Generics as requested by @VLAZ
type myFuncDef<T> = (x: T, y: T) => void;
myFunc: myFuncDef<A | B> = (x, y) => {};
If I use a typeguard inside myFunc to narrow down x to type A for example, y still unfortunately will not also narrow down to type A.
Clarification
I understand that I can use a single parameter and specify it to be of type AorB and it will work fine. I also understand that I can use two type guards to narrow the types inside myFunc; however, I would like to know if there is a way to group these types such that I can pass two parameters to myFunc and only have to use one type guard to narrow down both parameters?
I have a strong inclination this problem can be solved with generics, but I think I am just doing it incorrectly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
