typescript - 如何组合传递的泛型类型的属性

标签 typescript generics

如果我有一个类型:

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>将有一个idchildren属性(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)和类型别名之间存在一些差异,但在许多情况下它们是可以互换的。这是否确实是一个问题取决于您的用例。

Playground link to code

关于typescript - 如何组合传递的泛型类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76148974/

相关文章:

java - 尝试使用 ResponseEntity 和 RestTemplate 生成方法

java - 相同的删除,但类型不同。

css - 将 sass/css 模块添加到 typescript react app

c# - Windows 窗体设计器和通用窗体

javascript - 处理 "this"以访问类字段/方法

typescript - 在 TypeScript 中多态 this

java - 在 Java 中返回反向泛型列表类型

java - 通用 JNI 类型实例化

Angular 5. 相互导入类时 typescript 中的循环依赖

javascript - Typescript/Javascript for 在数组上循环,将键的值作为键值 1 推送到新数组 - 如果已经存在,则递增