typescript - 从联合类型创建的打字稿合并映射类型
问题描述
我正在尝试从联合类型的键创建映射类型。为了有一个最小的例子,类型简单地映射到它们自己。以下泛型返回预期结果
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如果它可以提供帮助,我正在尝试修复这条线。
解决方案
是的,这是预期的行为,它通常是称为分布式条件类型的有用功能。
但有时,就像在您的示例中一样,它会妨碍您。解决方法是在条件测试中使用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
推荐阅读
- .htaccess - .htaccess url 重写删除字符串
- python - 使用run.py在一次运行中在机器人框架中运行具有各自排除标记的不同测试套件?
- android - 使用 FirestoreRecyclerAdapter 单击 RecyclerView 时在新集合中添加项目
- c# - 如何为方法中使用的对象建模(UML,类图)
- c# - Rhino Mocks 使用存根函数的输入参数来创建返回值
- google-apps-script - 添加 ALERT onEdit - Google 表格/Google Apps 脚本
- python - 如果我使用 pandas 对同一项目同时拥有 True 和 False 行,则获取 True 行
- android - 如果 WebView 遵循替代链接,则返回时会进入无限循环
- python - 如何根据 PID 获取正在运行的 IE 实例
- javascript - phpmyadmin+mysql 实时拉取数据