从联合类型创建的Typescript合并映射类型

从联合类型创建的Typescript合并映射类型,typescript,Typescript,我正在尝试从联合类型的键创建映射类型。为了获得一个简单的示例,这些类型只是映射到它们自己。以下泛型返回预期结果 type Foo={[条形图中的名称]:name} 类型test=Foo//test={test1:'test1',test2:'test2'} 但是,如果Bar不是字符串,我想删除字符串containt并返回undefined。我是这样做的 type Foo=Bar扩展字符串?{[条形图中的名称]:名称}:未定义 型式试验=Foo //预期结果:test={test1:'test1

我正在尝试从联合类型的键创建映射类型。为了获得一个简单的示例,这些类型只是映射到它们自己。以下泛型返回预期结果

type Foo={[条形图中的名称]:name}
类型test=Foo//test={test1:'test1',test2:'test2'}
但是,如果
Bar
不是字符串,我想删除字符串containt并返回
undefined
。我是这样做的

type Foo=Bar扩展字符串?{[条形图中的名称]:名称}:未定义
型式试验=Foo
//预期结果:test={test1:'test1',test2:'test2'}
//实际结果:test={test1:'test1'}{test2:'test2'}
test
现在是联合类型,而不是简单的映射类型

这是typescript中的预期行为还是我应该提交错误报告?有没有什么方法可以达到我想要的行为


顺便说一句,如果有帮助的话,我正在尝试修复线路。

是的,这是预期的行为,它通常是有用的功能

但有时候,就像你的例子,它会妨碍你。解决方法是将
类型参数包装在
[]
中:

type Foo1={[条形图中的名称]:name}
类型test1=Foo1//test1={test1:'test1',test2:'test2'}
类型Foo2=[Bar]扩展[string]?{[条形图中的名称]:名称}:未定义;
类型test2=Foo2//test2={test1:'test1',test2:'test2'}
类型test3=Foo2;//未定义
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