Reputation: 21
I want to declare a type in typescript ApiResponse and mention 3 keys in it which are isError, error, and content. What I want is that type should be declared as such that either isError and error exist or content exists.
type ApiResponse<T> = {
isError?: boolean;
error?: ErrorContent;
content: this.isError ? undefined : User; // this is something I want . how should I do it.
}
I want this so that when I call a function which wants a parameter of User type doesn't give an error that the parameter is undefined
Upvotes: 1
Views: 60
Reputation: 36127
We can't define type based on dynamic value here,
User
typestatus
kind of enumeration (success, error
)so that we represent invalid state properly. Try like below,
type ErrorContent = {};
type User = {};
interface SuccessResponse<T> {
status: "success";
content: T; // this is something I want . how should I do it.
}
interface ErrorResponse {
status: "error";
error: ErrorContent;
}
type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;
const success: ApiResponse<User> = {
status: "success",
content: {}
};
const failure: ApiResponse<User> = {
status: "error",
error: {},
};
Upvotes: 1
Reputation: 4173
It is impossible to define type differently by variable. Simply you can define the type using |
operator.
type ApiResponse<T> = {
isError?: boolean;
error?: ErrorContent;
content: User | undefined;
}
Upvotes: 1