【问题标题】:Typescript merge mapped type created from union type从联合类型创建的打字稿合并映射类型
【发布时间】:2019-12-11 13:25:25
【问题描述】:

我正在尝试从联合类型的键创建映射类型。为了有一个最小的例子,类型简单地映射到它们自己。以下泛型返回预期结果

type Foo<Bar extends string> = {[name in Bar]: name}
type test = Foo<'test1' | 'test2'> //test = {test1: 'test1', test2: 'test2'}

但是,如果Bar 不是字符串,我想删除字符串约束并返回undefined。我通过以下方式做到了这一点

type Foo<Bar> = Bar extends string ? {[name in Bar]: name} : undefined
type test = Foo<'test1' | 'test2'>
//expected result: test = {test1: 'test1', test2: 'test2'}
//actual result: test = {test1: 'test1'} | {test2: 'test2'}

test 现在是联合类型而不是简单的映射类型。

这是打字稿中的预期行为还是我应该提交错误报告?有什么方法可以得到我想要的行为吗?

附:如果它可以提供帮助,我正在尝试修复this 行。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    是的,这是预期的行为,它通常是称为 distributive conditional types 的有用功能。

    但有时,就像在您的示例中一样,它会妨碍您。解决方法是将Bar类型参数包裹在[]when it's used in condition test中:

    type Foo1<Bar extends string> = {[name in Bar]: name}
    type test1 = Foo1<'test1' | 'test2'> //test1 = {test1: 'test1', test2: 'test2'}
    
    type Foo2<Bar> = [Bar] extends [string] ? {[name in Bar]: name} : undefined;
    type test2 = Foo2<'test1' | 'test2'> //test2 = {test1: 'test1', test2: 'test2'}
    type test3 = Foo2<1>; // undefined
    

    【讨论】:

      猜你喜欢
      • 2021-01-26
      • 1970-01-01
      • 2020-06-07
      • 2022-08-17
      • 2022-08-16
      • 1970-01-01
      • 2020-10-01
      • 2021-07-08
      • 2017-05-18
      相关资源
      最近更新 更多