chuckd
chuckd

Reputation: 14520

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.

Can I use a specific value other than 'any' as the data property type? I want to be able to use either 'IYogaEvent[]' or 'IUser[]' but can only figure out how to give data a type of 'any'

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[] = [];
}

Upvotes: 0

Views: 29

Answers (1)

antoinestv
antoinestv

Reputation: 3306

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;
}

Upvotes: 1

Related Questions