ken
ken

Reputation: 9013

How do you write an interface with a generic which is always an array?

I have a generic function:

export function limitToApiContraints<T extends Array>(payload: T, type: IQueueTypes) {
  ...
}

Unfortunately the signature of the generic errors out saying:

Generic type 'Array' requires 1 type argument(s).

If I change this to :

export function limitToApiContraints<T extends Array<any>>(payload: T, type: IQueueTypes) {
  return foo as T;
}

the function signature passes structural tests but when I return foo as T it comes back as ready: any[] | IGitHubRepoMap[] (where T = IGitHubRepoMap[]).

How can I state that T will always be an array but preserve a discreet type is returned?

Upvotes: 0

Views: 25

Answers (1)

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20043

Don't make the array property part of the definition of the generic, but instead use

function test<T>(payload: T[]) { ... } 

Upvotes: 3

Related Questions