What is the best way to type an API Response

I'm currently trying to type my API Response for a user login what would be the best way to type that response that could take either a 404 error or a successful ok response. This is somewhat correct but forces me to ensure that data is not null, but this doesn't seem like the correct approach when typing this response type. Is there a different way I can approach this by combining an error type and an ok type?
3 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
NinjaBunny
NinjaBunny2y ago
so I understand unions as a function param, but in the case where if I wanted to do something like
type Response<T> = { status: 'ok'; statusCode: number; data: T } | { status: 'error': statusCode: number; error: Error };

const response = await fetch<Response>('http://localhost:3000/api/auth/login', {
method: "GET",
headers: {
"Content-Type": "application/json",
},
body: {
email: email.toLowerCase(),
password,
},
});

if(response.status === 'ok') {
//do something
return;
}

//do error
type Response<T> = { status: 'ok'; statusCode: number; data: T } | { status: 'error': statusCode: number; error: Error };

const response = await fetch<Response>('http://localhost:3000/api/auth/login', {
method: "GET",
headers: {
"Content-Type": "application/json",
},
body: {
email: email.toLowerCase(),
password,
},
});

if(response.status === 'ok') {
//do something
return;
}

//do error
I guess this would be the logic on this then right? or something along these lines?
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server