【发布时间】: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