繁体   English   中英

如何根据同一类型中提到的键在打字稿中声明类型?

[英]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 类型参数的函数时,不会给出参数未定义的错误

我们不能在这里定义基于动态值的类型,

  1. 我们需要使用泛型来获取User类型
  2. 而不是 isError boolean 我们应该使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM