【问题标题】:TypeScript: Conditional type array of union type distributionTypeScript:联合类型分布的条件类型数组
【发布时间】:2021-12-09 16:02:59
【问题描述】:

我有一个条件类型,它使用泛型类型T 来确定@​​987654322@ 类型。作为一个人为的例子:

type X<T> = T extends string ? Array<T> : never;

我遇到的问题是,当我提供联合类型时,它被分发为 2 个数组类型的联合,而不是我的联合类型的数组。

// compiler complains because it expects Array<'one'> | Array<'two'>
const y: X<'one' | 'two'> = ['one', 'two'];

有没有办法输入这个,以便我的条件类型产生一个 Array条件是否满足?

【问题讨论】:

    标签: typescript discriminated-union


    【解决方案1】:

    您遇到了条件类型的分布行为,其中条件类型分布在包含联合的裸类型参数上。这种行为在某些情况下非常有用,但一开始可能会有点令人惊讶。

    禁用此行为的简单选项是将类型参数放入元组中:

    type X<T> = [T] extends [string] ? Array<T> : never;
    
    // ok y is Array<'one' | 'two'>
    const y: X<'one' | 'two'> = ['one', 'two'];
    

    您可以阅读有关此行为的更多信息 herehere

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 2020-02-25
      • 2019-03-26
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多