I have this interface, which consists of different dynamic keys (API Routes / paths), followed by a method and the response.
interface ApiRoutes {
"auth/login": {
POST: {
response: {
username: string;
token: string;
};
};
};
"users/me": {
GET: {
response: {
username: string;
name: string;
age: number;
};
};
};
}
I'm trying to write a type that will extract a response given the path and the method. My approach was the following:
type ApiResponse<
Path extends keyof ApiRoutes,
Method extends keyof ApiRoutes[Path]
> = ApiRoutes[Path][Method]["response"];
But the compiler complains, saying that "response" can't be used to index
Type '"response"' cannot be used to index type 'ApiRoutes[Path][Method]'.ts(2536)
Oddly enough, if I ignore the error, VS Code will still show suggestions/autocomplete the response object as if nothing happened.
const response: ApiResponse<"auth/login", "POST"> = {
username: "foo",
token: "bar",
};
Reference