Is there a way to use a pre-defined map of string to object types to determine both the return value and ensure type safety in an implemented function?
Let's take a look at this example:
import Axios from "axios";
export const axios = Axios.create();
type Foo = {
id: string;
name: string;
foo: number;
}
type Bar = {
id: string;
name: string;
bar: number;
}
type FooResponse = {
response: Foo[];
}
type BarResponse = {
response: Bar[];
}
type FooBarMap = {
foo: FooResponse;
bar: BarResponse;
}
const getFooBar = async <T extends keyof FooBarMap>(endpoint: T, query: Record<string, any> = {}) => {
const records: FooBarMap[T]["response"] = [];
const response = await axios.get<FooBarMap[T]>(`/${endpoint}`, query);
const data = response.data.response;
records.push(...data);
return records;
}
This scenario triggers the following error:
Argument of type 'Foo | Bar' is not assignable to parameter of type 'Foo & Bar'. Type 'Foo' is not assignable to type 'Foo & Bar'. Property 'bar' is missing in type 'Foo' but required in type 'Bar'.