简体   繁体   English

我可以在一个类中定义一个特定的类类型,该类在打字稿中实现了一个具有泛型类型的接口吗?

[英]Can I define a specific class type in a class that implements an interface with a generic type in typescript?

I have this interface and class that implements it below.我有这个接口和类在下面实现它。 It initially had data as a 'IYogaEvent[]' and now I want to use it for multiple items, so I created a generic to pass in.它最初将数据作为“IYogaEvent[]”,现在我想将它用于多个项目,因此我创建了一个泛型来传入。

Can I use a specific value other than 'any' as the data property type?我可以使用“any”以外的特定值作为数据属性类型吗? I want to be able to use either 'IYogaEvent[]' or 'IUser[]' but can only figure out how to give data a type of 'any'我希望能够使用“IYogaEvent[]”或“IUser[]”,但只能弄清楚如何为数据提供“任何”类型

 export interface IPagination <T> { pageIndex: number; pageSize: number; count: number; data: T; // data: IYogaEvent[]; // data: IUser[]; } export class Pagination implements IPagination <any> { pageIndex: number; pageSize: number; count: number; data: any; // data: IYogaEvent[] = []; // data: IUser[] = []; }

You should be able to do the same thing and forward the generic type:您应该能够做同样的事情并转发泛型类型:

export interface IPagination<T> {
  pageIndex: number;
  pageSize: number;
  count: number;
  data: T;
}

export class Pagination<T> implements IPagination<T> {
  pageIndex: number;
  pageSize: number;
  count: number;
  data: T;
}

暂无
暂无

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

相关问题 实现泛型类型的 Typescript 泛型类 - Typescript generic class that implements a generic type 为什么我不能在打字稿类中定义接口或类型 - why i can't define interface or type inside typescript class TypeScript:是否可以强制接口签名中的泛型类型与实现此接口的 class 类型相同 - TypeScript: is it possible to force a generic type in a interface signature that be of the same type of class that implements this interface Typescript - 实现泛型类型的类实例 - Typescript - Class instance which implements generic type TypeScript:实现某个接口或方法的 class 的类型 - TypeScript: type of class that implements a certain interface or method 如何定义“实现”接口的类型? - How can I define a type that “implements” an interface? 如何在Typescript中定义一个类,该类接受一个接口,该接口具有两个用于相同泛型的字段并保证它们是同一类型? - How do I define a class in Typescript that accepts an interface that has two fields for the same generic and guarantee they are the same type? 我可以为类的方法定义通用的打字稿接口吗? - Can I define a generic typescript Interface for the methods of a Class? 接口字段应具有实现该接口的类的类型-typescript - Interface field should have type of the class that implements that interface - typescript Typescript generics 对于类型 A 是 Class,B 是实现接口的 class<a></a> - Typescript generics for type A is a Class and B is a class that implements Interface<A>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM