Looking to create a type/interface with generics that has two properties:
interface Response<T> {
status: number;
data: T | undefined;
}
Specifically, I want to enforce a rule where if the status is not equal to 200, then data must be undefined. On the other hand, if the status is equal to 200, then data must be of type T. This would eliminate the need to always check if response.data is defined after verifying that response.status is 200:
if (response.status === 200 && response.data) {
// It would be ideal for TypeScript to automatically understand that response.data
// is not undefined without additional explicit checks
}
This is what I currently have:
interface IOkResponse<T> {
status: 200;
data: T;
}
interface IErrorResponse {
status: number;
data: undefined;
}
type Response<T> = IOkResponse<T> | IErrorResponse;
The issue lies in the fact that IErrorResponse does not restrict the status value to numbers other than 200. How can this restriction be implemented?