Home > front end >  Typescript Generic is not inferring the type
Typescript Generic is not inferring the type

Time:05-21

I've got a type where I need the part of the array to be generic but whatever I pass in that part of the array, the compiler fails.

export type ErrorFirstArray<Response> = [SanitisedError | null, Response | null | undefined];

export type HandleResponse = <Response>(
  response: AxiosResponse
) => ErrorFirstArray<Response>;

const handleResponse: HandleResponse = () => {
  return [null, 'foo']; // <--- doesn't like the string here
}

Type 'string' is not assignable to type 'Response | null | undefined'

Is there a better way to define ErrorFirstArray?

CodePudding user response:

HandleResponse is a generic function, this means the type parameter is decided by the caller, not the definition. You probably want a generic type, that is a function:

export type ErrorFirstArray<Response> = [SanitisedError | null, Response | null | undefined];

export type HandleResponse<Response> = (
  response: AxiosResponse
) => ErrorFirstArray<Response>;

const handleResponse: HandleResponse<string> = () => {
  return [null, 'foo'];
}

Playground Link

You might find this video useful for more explanations

  • Related