繁体   English   中英

typescript 接口与通用 object 参数

[英]typescript interface with a generic object parameter

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

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. 然后我如何找出用户通过了哪个 object?

谢谢你!

为了知道用户传递了哪种类型,您需要使用有区别的联合

为此,您应该:

  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) {
    // ...
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM