[英]How to declare a type in typescript based on the keys mentioned in the same type?
我想在 typescript ApiResponse 中声明一个类型,并在其中提及 3 个键,分别是 isError、error 和 content。 我想要的是该类型应该声明为 isError 和 error 存在或内容存在。
type ApiResponse<T> = {
isError?: boolean;
error?: ErrorContent;
content: this.isError ? undefined : User; // this is something I want . how should I do it.
}
我想要这个,这样当我调用一个需要 User 类型参数的函数时,不会给出参数未定义的错误
我们不能在这里定义基于动态值的类型,
User
类型status
类型的枚举( success, error
)以便我们正确表示无效状态。 尝试如下,
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: {},
};
不可能通过变量来定义不同的类型。 只需使用|
定义类型即可|
操作员。
type ApiResponse<T> = {
isError?: boolean;
error?: ErrorContent;
content: User | undefined;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.