[英]how to use generic this type in this case ? i don't know why
最近我了解到 typescript 通用。 我在某些情况下使用它。 但我不能。
当使用两个不同的接口时,我想要它。
例如
我想发送服务器请求。
function fetcher async(){
return await axios.get(url).then(data=>data.result)
}
服务器给了我回复,但是它们有两种不同的类型
// response A
interfase AInterface {
name: string;
age: number;
address: string
}
// response B
interfase BInterface {
name: string;
job : string;
haveCar: boolean;
}
并使用泛型设置返回类型
function fetcher<T> async():<T>{
return await axios.get(url).then(data=>data.result)
}
and use function
const result = fetcher<AInterface>()
or fetcher<BInterface>()
结果类型为 AInterface | B接口
为什么结果有类型 AInterface | B接口??
我不知道
我希望它有 AInterface 或 BInterface。 不是工会
你不需要输入fetcher
只需使用:
async function fetcher() {
const { data } = await axios.get<AInterface>(url)
return data
}
或者:
async function fetcher(): Promise<AInterface> {
const { data } = await axios.get(url)
return data
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.