简体   繁体   English

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

[英]How to declare a type in typescript based on the keys mentioned in the same type?

I want to declare a type in typescript ApiResponse and mention 3 keys in it which are isError, error, and content.我想在 typescript ApiResponse 中声明一个类型,并在其中提及 3 个键,分别是 isError、error 和 content。 What I want is that type should be declared as such that either isError and error exist or content exists.我想要的是该类型应该声明为 isError 和 error 存在或内容存在。

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我想要这个,这样当我调用一个需要 User 类型参数的函数时,不会给出参数未定义的错误

We can't define type based on dynamic value here,我们不能在这里定义基于动态值的类型,

  1. one we need to use generic to get User type我们需要使用泛型来获取User类型
  2. Instead of isError boolean we should use status kind of enumeration ( success, error )而不是 isError boolean 我们应该使用status类型的枚举( 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: {},
};

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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