I'm currently diving into TypeScript and trying to accomplish something that I'm not entirely sure is possible (but I believe it is).
Here's an example of the code I have:
interface HttpServiceMockData<T> {
status: number;
data: T;
url: string;
}
export function createHttpServiceMock<T>(data: HttpServiceMockData<T>[]) {
return {
get: async (url: string): Promise<{ data: T }> => {
const res = data.find((d) => d.url === url);
if (!res) {
throw new Error(`No data found for url ${url}`);
}
return {
data: res.data,
};
},
};
}
const service = createHttpServiceMock([
{
url: '/users/1',
data: {
id: 1,
username: 'test',
},
status: 200,
},
{
url: 'test',
data: {
id: 1,
username: 'test',
lastname: 'test',
},
status: 200,
},
]);
const res = service.get('test').then((res) => {
res.data // I wish for TypeScript to accurately recognize the type here (inference power)
});
Currently, TypeScript is aware of what needs to be returned but lacks precise information about the structure of the data object, hence providing "lastname" as optional, which doesn't align with my requirements.
I intend to input the URL and have TypeScript automatically understand my desired output.
Any thoughts on how to achieve this?