So I have a wrapper for api calls to a strapi server
export const api = {
post: async<T extends unknown, K>(url: string, body: Partial<T>, jwt?: string): Promise<K> => {
try {
const result = await postData<Partial<T>, K>(url, body, jwt);
return result;
} catch (e) {
throw e;
}
},
};
I am trying to get it so K is optional so I can do the follow
await api.post<type1, type2>(url, body);
await api.post<type1>(url, body);
I have tried
export const api = {
post: async<T extends unknown, K = undefined>(url: string, body: Partial<T>, jwt?: string): Promise<K | T> => {
try {
const result = await postData<Partial<T>, K | T>(url, body, jwt);
return result;
} catch (e) {
throw e;
}
},
};
but I would either get typing errors because it would be missing a field from type1 when the return type should only be type2 or I would get that the return object could possibly undefined.
I was wondering if it is possible to have it so if both types are used for the post function, it will use the second type as the return type or use the first type as the return type?
Full Example that can be pasted into typescript playground with comments where the errors occurred
const api = {
post: async<T extends unknown, K = undefined>(url: string, body: Partial<T>, jwt?: string): Promise<K | T> => {
try {
const result = await postData<Partial<T>, K | T>(url, body, jwt);
return result;
} catch (e) {
throw e;
}
},
};
function postData<K, T>(url: string, data: K, jwt: string = '', failOnNotOk: boolean = true): T {
const request: T = (data) as any;
return request;
}
type user = {
email: string;
password: string;
}
type res = {
valid: string;
}
(async () => {
const url: string = 'https://google.com';
const body: user = {
email: 'test@example.com',
password: 'test1234',
};
// this gives an error about result having the possibility of being undefined
const result = await api.post<user>(url, body);
console.log(result.email);
// returns an errror about valid not being a field on user when the return type should only be res
const res = await api.post<user, res>(url, body);
console.log(res.valid);
})();