generics - 有没有办法用 TypeScript 泛型进行传播操作?

标签 generics typescript

我有一个函数接收一个对象并将其与另一个对象合并。我希望能够有一个通用的 T,它代表正在接受的对象,因为 Typescript 知道输出对象包含相同的键,但也有新的键。

export interface ObjFactory<T> {
  someNewProp: string
  otherNewProp: string
  ...T
}

export interface InputObject {
  inputProp: string
}

那么输出对象将表示为

{
  someNewProp: string
  otherNewProp: string
  inputProp: string
}

有没有办法实现类似的东西?

最佳答案

你可以使用 Type Intersection如果您愿意导出 type 而不是接口(interface),则可以实现此目的。

export type ObjFactory<T> = T & {
  someNewProp: string
  otherNewProp: string
}

export interface InputObject {
  inputProp: string
}

type AFAIK 的唯一缺点是类和接口(interface)不能扩展它们。

关于generics - 有没有办法用 TypeScript 泛型进行传播操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42179024/

相关文章:

c# - 为什么这段代码要用 long 代替 float 呢?

Java:ArrayList 返回对象而不是所需的类型

generics - Newtype 作为 Rust 中的泛型参数?

java - 如何比较相同类型的泛型?

typescript - 在引用其他命名空间的同时导出环境声明中的命名空间

typescript - Vue.js 路由器不调用 beforeRouteUpdate( typescript )

typescript - 如何确定哪个 Jest 测试在超时内无法运行?

Java:我的 classOf 和 newArray 怎么样?

javascript - 在 tsc TypeScript 编译中包含 CSS 文件

javascript - 如何在括号中编写 TypeScript 和 CoffeeScript?