【发布时间】:2020-09-28 18:57:50
【问题描述】:
我很难弄清楚如何在这里创建我的and 函数:它的工作很简单。它必须接受一堆项目,并将它们连接成一个以"and"开头的数组
// the items 'and' may accept
type Item = false
| {type: "alpha", a: boolean}
| {type: "bravo", b: number}
// 'and' function adds items to an array
function and<Items extends Item[]>(
...items: Items
): ["and", ...Items] {
return ["and", ...items]
}
// calling 'and' with a few items
const [op, item1, item2, item3] = and(
false,
{type: "alpha", a: true},
{type: "bravo", b: 3.14},
)
// verifying the types are preserved
op //> ✔ type "and"
item1 //> ✘ type Item, expected false
item2 //> ✘ type Item, expected {type: "alpha", a: true}
item3 //> ✘ type Item, expected {type: "bravo", b: 3.14}
问题是 item1、item2 和 item3 都丢失了它们原来的特定类型信息,因此我的 and 函数实际上是对类型的破坏性操作——相反,我需要保留类型
有不同的方法吗?谢谢!
【问题讨论】:
标签: typescript