[英]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.
}
谢谢你!
为了知道用户传递了哪种类型,您需要使用有区别的联合。
为此,您应该:
kind
或type
或任何你喜欢的属性,以便区分它们:interface Recipe {
type: 'Recipe',
title: string,
ingredients: []
creator: string,
// ...
}
interface Vendor {
type: 'Vendor',
name: string
address: Address
// ...
}
type Entity /* or whatever */ = Recipe | Vendor;
现在 TS 可以根据 type 属性了解使用了哪个特定接口
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.