首页 > 解决方案 > 从联合类型创建的打字稿合并映射类型

问题描述

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

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

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

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现在是联合类型而不是简单的映射类型。

这是打字稿中的预期行为还是我应该提交错误报告?有没有办法得到我想要的行为?

PS如果它可以提供帮助,我正在尝试修复条线。

标签: typescript

解决方案


是的,这是预期的行为,它通常是称为分布式条件类型的有用功能。

但有时,就像在您的示例中一样,它会妨碍您。解决方法是在条件测试中使用Bar类型参数时将其包装起来:[]

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

推荐阅读