假设我想要编写一个简单的泛型连接函数。
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应该是一个字符串,它指定函数应该联接在哪个属性上。
遗憾的是,我得到了一个错误:T cannot be used to index type Y
这很奇怪,因为X & Y是交叉点类型,因此扩展keyof表达式生成的所有键都应该应用于X和Y。
发布于 2021-04-06 23:27:56
我猜,您对交叉点类型的假设是错误的:
interface X {
x: number
};
interface Y {
y: number
}
type Inter = X & Y;
type InterK = keyof Inter; // = 'x' | 'y'您真正想要的是只获取两种类型中相同的类型。
有关Common<>的说明,请参阅: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'https://stackoverflow.com/questions/66971313
复制相似问题