【问题标题】:TypeScript: Exclude Union String Literal Value from Interface KeyTypeScript:从接口键中排除联合字符串文字值
【发布时间】:2022-01-18 10:54:55
【问题描述】:

我有一个这样的界面。

interface ITest {
  key1?: string;
  key2?: 'apple' | 'orange' | 'cherry' | 'grape';
}

问题

如何在扩展 ITest 的同时从 key2 联合类型中排除特定的字符串文字值?

我知道我可以使用Exclude 来完全删除key2,但我怎么能保留key2 但从其联合类型中排除特定值?

我尝试过类似但没有运气的东西。不确定这是否仅适用于实用程序类而不创建单独的 Fruit 类型,例如并在其上使用 Exclude

Exclude<Pick<ITest, 'key2'>, 'apple' | 'grape'>

【问题讨论】:

    标签: typescript types interface


    【解决方案1】:
    • 获取除 key2 之外的所有属性
    • 添加带有排除元素的 key2
    interface ITest {
      key1?: string;
      key2?: 'apple' | 'orange' | 'cherry' | 'grape';
    }
    
    type I2 = Omit<ITest, 'key2'> & {
      key2?: Exclude<ITest['key2'], 'apple' | 'grape'>
    }
    
    // alternative way
    type I3 =  { 
      [P in keyof ITest]: P extends 'key2' 
      ? Exclude<ITest['key2'], 'apple' | 'grape'> 
      : ITest[P] 
    }
    

    Playground link

    【讨论】:

    • 太棒了!我不知道括号符号选项。有没有办法一次完成所有操作,而不是将密钥重新添加到新界面? (现在主要是好奇)
    • @Yuschick 添加了另一种编码方式
    • 感谢您的示例。我想我更喜欢你的第一种方法,但我很感激你向我展示了我很好奇的替代方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2021-12-25
    • 2017-05-07
    • 2018-01-18
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多