【问题标题】:Why doesn't using keys from two sides of a union cause TS to complain?为什么不使用联合两侧的密钥导致 TS 抱怨?
【发布时间】:2019-09-13 04:34:03
【问题描述】:

为什么这不会导致 TS 错误? TS playground

type T = { a: string } | { b: string }

const obj: T = {
  a: 'a',
  b: 'd',
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    为了获得互斥性和多余的财产检查,一种解决方法是这样做

    export type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;
    export type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
    
    
    type T = XOR<{ a: string }, { b: string }>
    
    const obj: T = {
      a: 'a',
    } // passes
    
    const obj1: T = {
      b: 'b',
    } // passes
    
    const obj2: T = {
      a: 'a',
      b: 'b',
    } // fails
    

    【讨论】:

      【解决方案2】:

      因为唯一会导致 TS 抱怨的是excess property check,而对于非区分联合类型则不会这样做。 There's open issue for that,2017 年 12 月 22 日报道。

      另见Union type does not act as mutual exclusion,答案是“它从未打算这样做”。

      【讨论】:

        猜你喜欢
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 1970-01-01
        • 2017-01-17
        • 2021-10-28
        • 1970-01-01
        • 2015-06-09
        相关资源
        最近更新 更多