如何根据同一类型中提到的键在打字稿中声明一个类型?
How to declare a type in typescript based on the keys mentioned in the same type?
我想在 typescript ApiResponse 中声明一个类型,并在其中提及 3 个键,它们是 isError、error 和 content。我想要的是类型应该声明为 isError 和错误存在或内容存在。
type ApiResponse<T> = {
isError?: boolean;
error?: ErrorContent;
content: this.isError ? undefined : User; // this is something I want . how should I do it.
}
我想要这个,这样当我调用一个需要用户类型参数的函数时,不会给出参数未定义的错误
我们不能在这里定义基于动态值的类型,
- 我们需要使用泛型来获得
User
类型
- 我们应该使用
status
类型的枚举 (success, error
) 而不是 isError 布尔值
这样我们就可以正确地表示无效状态。像下面这样尝试,
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;
}
我想在 typescript ApiResponse 中声明一个类型,并在其中提及 3 个键,它们是 isError、error 和 content。我想要的是类型应该声明为 isError 和错误存在或内容存在。
type ApiResponse<T> = {
isError?: boolean;
error?: ErrorContent;
content: this.isError ? undefined : User; // this is something I want . how should I do it.
}
我想要这个,这样当我调用一个需要用户类型参数的函数时,不会给出参数未定义的错误
我们不能在这里定义基于动态值的类型,
- 我们需要使用泛型来获得
User
类型 - 我们应该使用
status
类型的枚举 (success, error
) 而不是 isError 布尔值
这样我们就可以正确地表示无效状态。像下面这样尝试,
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;
}