recently i learned typescript generic. and i used it in certain situations. but i couldn't.
When using two different interfaces, i wanted it.
for example
i wanna send server request.
function fetcher async(){
return await axios.get(url).then(data=>data.result)
}
and server gives me responses but, they have two different types
// response A
interfase AInterface {
name: string;
age: number;
address: string
}
// response B
interfase BInterface {
name: string;
job : string;
haveCar: boolean;
}
and set return type by using generic
function fetcher<T> async():<T>{
return await axios.get(url).then(data=>data.result)
}
and use function
const result = fetcher<AInterface>()
or fetcher<BInterface>()
result has type AInterface | BInterface
why does result have type AInterface | BInterface ??
i don't know
i want it has AInterface or BInterface . Not union
You dont need to type fetcher
just use:
async function fetcher() {
const { data } = await axios.get<AInterface>(url)
return data
}
Or:
async function fetcher(): Promise<AInterface> {
const { data } = await axios.get(url)
return data
}