【问题标题】:Extend a partial with excludes ignores the excluded properties [duplicate]使用排除扩展部分忽略排除的属性[重复]
【发布时间】:2019-10-09 22:27:28
【问题描述】:

我不确定我是否误解了Exclude 的工作原理,但我有以下问题:

export interface Base {
    page: number;
    count: number;
}

export interface Sub extends Partial<Exclude<Base, 'count'>> { // error
    count?: 'nonzero'|'zero';
}

接口Sub 导致错误提示Sub 错误地扩展了接口Partial&lt;Base&gt;,但这不是我所期望的。我期待Sub 扩展Partial&lt;{ page: number }&gt;,这是我认为是Exclude&lt;Base, 'count'&gt; 的类型,但它似乎并非如此。

Playground

【问题讨论】:

    标签: typescript


    【解决方案1】:

    Exclude 从联合中删除了一个类型。例如Exclude&lt;'a' | 'b', 'b'&gt; 将是a。它不会从类型中删除属性。

    通常,从另一个类型中删除属性的类型称为OmitOmit 将包含在 3.5 中,但是根据 PickExclude 定义很简单(下面实际上是 Omit 的 3.5 定义):

    type Omit<T, K extends PropertyKey> = Pick<T, Exclude<keyof T, K>>
    export interface Base {
        page: number;
        count: number;
    }
    
    export interface Sub extends Partial<Omit<Base, 'count'>> { // ok
        count?: 'nonzero'|'zero';
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 2020-02-20
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 2011-10-27
      • 2014-07-15
      • 1970-01-01
      相关资源
      最近更新 更多