Emille C.
Emille C.

Reputation: 365

Generic with a type alias

I am trying to create a mock function for async testing in TypeScript. My function receives some data, and returns it when promise resolves.

I know I can type it like this:

type Options<T> = {
  data: T;
};

export const mockApiCall = async <T>({ data }: Options<T>): Promise<{ data: T }> => {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ data }), 100);
  });
};

But I would like to do it with a type alias in the function name, like this:

type Options<T> = {
  data: T;
};

type MockData<T> = (options: Options<T>) => Promise<{ data: T }>;

export const mockApiCall: MockData<T> = async ({ data }) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ data }), 100);
  });
};

But it returns the error Cannot find name 'T'.ts(2304).

What is the correct syntax for this?

Upvotes: 0

Views: 540

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

The placement of your generic type parameter is wrong. You want a generic function (the type parameter to be on the function) not a generic type that happens to be a function. The difference is that a generic function has its type parameters decided when it is invoked. A generic type needs to have its type parameters decided when it is used.

type Options<T> = {
  data: T;
};

type MockData = <T>(options: Options<T>) => Promise<{ data: T }>;

export const mockApiCall: MockData = async ({ data }) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ data }), 100);
  });
};

Playground Link

Upvotes: 3

Alexander Kosykh
Alexander Kosykh

Reputation: 371

You can try this code:

type Options<T> = {
  data: T;
};

export const mockApiCall = async <T>({ data }: Options<T>) => {
  return new Promise<Options<T>>((resolve) => {
    setTimeout(() => resolve({ data }), 100);
  });
};

Upvotes: 0

Related Questions