My goal is to establish a type alias in TypeScript that allows all values which are arrays of Domino pairs, where each pair connects like domino bricks: Pair<A,B> connects with Pair<C,D> only if B = C.
For example:
const chain1: DominoChain = [ ["A", "B"], ["B", "C"], ["C", "D"], ["D", "E"] ] // Accepted
const chain2: DominoChain = [ [3, 4], [4, 2], [2, 1] ] // Accepted
const chain3: DominoChain = [ [3, null], [null, {}], [{}, undefined] ] // Accepted
const chain4: DominoChain = [ [1, 2] ] // Accepted
const chain5: DominoChain = [ ] // Accepted
const chain6: DominoChain = [ [1, 2], [3, 4] ] // Not accepted due to 2 != 3. Compiler error expected.
I have made some attempts but it's not functioning as intended:
type Domino<A,B> = [A, B]
type DominoChain<A = any, B = any> = [Domino<A, B>] | [Domino<A, B>, ...DominoChain<B, any>]
I am unsure how to correctly enforce the matching constraint between two Domino pairs and I suspect there may be an issue with the recursive aspect.