【问题标题】:Is it possible to remove a wider type from an literal union in Typescript?是否可以从 Typescript 的文字联合中删除更广泛的类型?
【发布时间】:2023-01-11 16:46:13
【问题描述】:

我正在使用 React 和 Typescript,构建自定义输入组件,我希望从 input 元素中的 type 属性中清除允许的值,以防止意外用作“按钮”和“隐藏”。

type 属性的类型为 HTMLInputTypeAttribute,这是一个以 (string & {}) 结尾的联合类型。我不希望组件接收联合中未描述的类型值。

使用 Exclude 实用程序类型会导致 never,因为所有文字类型都从字符串扩展

我已经看过其他问题,比如How can I remove a wider type from a union type without removing its subtypes in TypeScript?,但由于他们的意图不一定与之前建立的工会有关,所以没有一个答案能满足我的需要

这有可能吗?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    你需要使用Distributive conditional types

    type Union = 'a' | 'b' | string & {}
    
    type ObtainLiterals<T> = T extends infer R ? R extends string ? string extends R ? never : R : never : never
    
    // 'a' | 'b'
    type Test = ObtainLiterals<Union>
    

    Playground

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 2016-07-22
      • 2019-12-05
      • 2018-03-01
      • 2019-12-10
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2019-11-04
      相关资源
      最近更新 更多