Reputation: 365
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
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);
});
};
Upvotes: 3
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