如果我有一个类型:
interface Item {
id: string
children: Array<Item>
}
如何修改它以使其成为泛型,以便它结合 Item
的属性和传递的泛型类型 T
。
示例:
interface WithLabel {
label: string
}
const item: Item<WithLabel> = {id: "x", label: "y", children: []};
console.log(`id=${item.id}, label=${item.label}`)
这可能吗?
最佳答案
如果你想制作Item
一个generic表单类型Item<T>
其中它具有 T
的所有属性,那么您需要将其更改为 type
alias而不是 interface
type ,和intersect您之前对 Item
的定义与 T
:
type Item<T> = {
id: string,
children: Array<Item<T>>
} & T;
两种类型的交集具有每种类型的所有属性,因此 Item<T>
将有一个id
和children
属性(property)以及 T
的所有属性(property):
interface WithLabel {
label: string
}
const item: Item<WithLabel> = {
id: "x",
label: "y",
children: []
}; // okay
console.log(`id=${item.id}, label=${item.label}`) // okay
它必须是类型别名而不是接口(interface)类型的原因是接口(interface)需要具有静态已知的键。但一些Item<T>
的 key 只知道一次 T
已指定,因此它不能是接口(interface)。接口(interface)和类型别名之间存在一些差异,但在许多情况下它们是可以互换的。这是否确实是一个问题取决于您的用例。
关于typescript - 如何组合传递的泛型类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76148974/