0

Lets say I want to write a simple generic join function.

const join = <X, Y, T extends keyof (X & Y)>(key: T, a1: Array<X>, a2: Array<Y>) =>
    a1.map(e1 => [ e1, a2.find(e2 => e2[key] === e1[key]) ])

T should be a string which specifies on which attribute the function should join.

Sadly I get an error: T cannot be used to index type Y

This is weird since X & Y is the intersection type thus all keys generated by the extends keyof expression should apply on X and on Y.

Arwed Mett
  • 2,614
  • 1
  • 22
  • 35

1 Answers1

0

I guess, your assumption about the intersection type is wrong:

interface X  {
    x: number
};
interface Y {
    y: number
}
type Inter = X & Y;
type InterK = keyof Inter; // = 'x' | 'y'

What you actually want is to get only the types that are the same in both types.

for description of Common<> see: https://stackoverflow.com/a/47379147/1041641

type Common<A, B> = {
    [P in keyof A & keyof B]: A[P] | B[P];
}

interface X2  {
    x: number
};
interface Y2 {
    y: number,
    x: string
}
type Inter2 = Common<X2, Y2>;
type InterK2 = keyof Inter2; // = 'x'

Playground link

TmTron
  • 17,012
  • 10
  • 94
  • 142