My API response comes in the form of a IResponse
, which can have different variations based on a URL search parameter.
Here is how I plan to utilize it:
const data1 = await request<E<"aaa">>('/api/data/1?type=aaa');
const data2 = await request<E<"bbb">>('/api/data/1?type=bbb');
function request<T>(
url: string
): Promise<T> {
return fetch(url, config)
.then((response) => response.json())
.then((data) => data as T);
}
//index.ts
import {
paths,
} from "./autoGeneratedTypes";
type IResponse =
paths["/api/data/{id}"]["get"]["responses"]["200"]["content"]["application/json"];
export type E<T extends "aaa" | "bbb"> = T extends "aaa"
? Omit<IResponse, "ca">
: Pick<IResponse, "ca">;
export type F = E<"aaa">["bb"];
Encountering an error at
Pick<IResponse, "ca">
stating Type 'string' does not satisfy the constraint 'never'
To avoid directly referencing schemas C
or B
due to possible schema name changes, I require a type that will correctly extract the API response type from IResponse
.
//autoGeneratedTypes.ts
/**
* This file was auto-generated by openapi-typescript.
* Do not make direct changes to the file.
*/
export interface paths {
"/api/data/{id}": {
/** @description get the data */
get: {
responses: {
/** @description Retrieved the data successfully */
200: {
content: {
"application/json": components["schemas"]["D"];
};
};
};
};
};
}
export interface components {
schemas: {
D: components["schemas"]["C"] | components["schemas"]["B"];
C: {
ca: components["schemas"]["B"][];
};
B: {
ba: string;
bb: components["schemas"]["A"][];
};
A: {
aa: string;
ab: string | null;
};
};
}