typescript - TypeScript: tuple type to object type
问题描述
Consider a tuple like this:
type MyTuple = [A, B];
where A
and B
both have an attribute named key
. For instance,
interface A = {
key: 'sandwiches'
}
interface B = {
key: 'pasta'
}
I desire the following interface:
interface Result {
sandwiches: A;
pasta: B;
}
Is there a way to do this dynamically?
I'm thinking that, if this is achievable, it might look something like:
type MapTuple<T> = {
[K in keyof T]: T[K]["key"]
}
but this doesn't work.
This question is the inverse of Typescript: object type to array type (tuple)
解决方案
这将产生预期的效果。您需要映射元组的所有键属性并为每个键提取元组成员:
type MyTuple = [A, B];
interface A {
key: 'sandwiches'
}
interface B {
key: 'pasta'
}
type MapTuple<T extends Array<{ key: string }>> = {
[K in T[number]['key']]: Extract<T[number], { key : K}>
}
type R = MapTuple<MyTuple>
推荐阅读
- bash - BASH 仅在单个字母不在单词中时替换单个字母
- javascript - 如何从 element.all each 返回一个元素
- php - 与 MongoDB 的 PHP 连接不起作用并响应“试图获取无价值的属性”
- python - 如何跳过按 Enter 继续使用 python 在 shell 命令中
- android - Phaser 2:游戏不加载到 WebView
- quickbooks - Consolibyte QuickBooks PHP 库 - 您如何调试/查看错误?
- linux - 在 Linux 中添加脚本以在启动终端 bash shell 时显示日期
- java - 如果测试失败,重试 TestNG 代码中的特定代码,而不是整个测试
- python - 如何在 Pandas 单元格中生成字符串计数的 Python 数据透视表?
- django - URLconf 中似乎没有任何模式/循环导入错误