如果没有加载并且没有错误,则rest调用应以T形式返回数据



当使用fetch在react钩子中发布数据时,是否可以推断,如果加载完成,并且没有错误,则数据不是null?

type apiReturn<T> = {
data:T | null,
loading:boolean,
error?: Error
}
type message = {
msg:string
}
const apiPost = <T>(body:T):apiReturn<T> => {
const [state, setState] = useState<apiReturn<message>>({data:null,loading:true,error:undefined})
useEffect(()=>{
const httpCall = fetch(url,{...postrequest, body:body}).then((resp) => {
if (resp.parsedBody === undefined){
setState({ data:null,loading: false, error:new Error("Oops... Something went wrong!") });
}
setState({ data:response.parsedBody,loading: false });

},[fetch,setState])
return state
}
const usePost = (data:message) => {
const apiresponse = apiPost(data)
if(!apiresponse.loading && apiresponse.error === undefined)
//Possibly undefined, but should be defined as everything went okey
const test:message = apiresponse.data
}

您可以使用有区别的并集:


type ApiReturn<T> = {
loading: true,
} | {
loading: false,
error?: undefined,
data: T,
} | {
loading: false,  
error: Error,
data?: null,
}
type message = {
text: string
}
const apiPost = <T extends object>(body: T): ApiReturn<T> => {
return null! // Implementation here
}

const usePost = (data: message) => {
const apiresponse = apiPost(data)
if (!apiresponse.loading && apiresponse.error === undefined) {
const test: message = apiresponse.data
}
}

游乐场链接