【问题标题】:Extends keyof Type Intersection扩展 keyof Type Intersection
【发布时间】:2021-07-02 09:28:24
【问题描述】:

假设我想编写一个简单的通用连接函数。

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 &amp; Y 是交集类型,因此由 extends keyof 表达式生成的所有键都应该应用于 X 和 Y。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我猜,你对交集类型的假设是错误的:

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

    您真正想要的是只获取两种类型中相同的类型。

    Common&lt;&gt; 的描述见: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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 2013-01-07
      • 2021-09-12
      相关资源
      最近更新 更多