【问题标题】:typescript interface with a generic object parameter带有通用对象参数的打字稿接口
【发布时间】:2020-08-10 23:22:03
【问题描述】:

我的应用中有多个对象。例如:

interface Recipe {  
  title: string,  
  ingredients: []  
  creator: string,  
  // ...  
}

interface Vendor {  
  name: string
  address: Address  
  // ...  
}

用户应该能够创建可以接受任何这些接口的对象,例如:

interface Event<T> {  
  date: Date(),  
  type: T // This should be of type Recipe or Vendor object for example.  
}
  1. 正确的定义方法是什么?
  2. 然后我将如何找出用户传递了哪个对象?

谢谢!

【问题讨论】:

  • 嗨@Agata!我不确定,你是什么意思“定义这个的正确方法”?您已经正确定义了一个可以接受通用类型的事件。您想强制类型 nly 为“Recipe”或“Vendor”之一吗?
  • 是的。我也不清楚如何识别用户通过了哪个对象?
  • 您可以使用UnionsExample

标签: typescript object generics interface


【解决方案1】:

要知道用户传递的是哪种类型,需要使用discriminated unions

为此,您应该:

  1. 添加kindtype 或任何您喜欢的属性来扩充接口,以便区分它们:
interface Recipe {  
  type: 'Recipe',
  title: string,  
  ingredients: []  
  creator: string,  
  // ...  
}

interface Vendor {  
  type: 'Vendor',
  name: string
  address: Address  
  // ...  
}
  1. 定义包含可用对象的联合类型
type Entity /* or whatever */ = Recipe | Vendor;

现在 TS 可以根据 type 属性了解使用了哪个特定接口

  1. 给定联合类型定义事件
interface Event<T extends Entity> {  
  date: Date,  
  type: T['type'], // If you need only the type
  object?: T
}

const event: Event<Recipe> = {
  date: Date,
  type: 'recipe',
  object: recipe
}

function <T extends Entity>(event: Event<T>) {
  switch (event.type) {
    // ...
  }
}

【讨论】:

  • 谢谢!我在哪里声明类型。您能否也举个例子,我将如何实例化这个接口?
  • 你可以在接口之后或之前声明类型,没关系。我将使用事件示例更新答案。
  • 不客气。如果答案让您满意,请接受它,以便其他用户知道它有效。
猜你喜欢
  • 2019-09-28
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2021-11-13
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
相关资源
最近更新 更多