Home > front end >  Generic with a type alias
Generic with a type alias

Time:01-13

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?

CodePudding user response:

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

CodePudding user response:

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 it's type parameters decided when it is invoked. A generic type needs to have it's 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

  •  Tags:  
  • Related