【问题标题】:How to conditional remove a property from an interface in Typescript如何有条件地从 Typescript 中的接口中删除属性
【发布时间】:2021-06-16 18:10:25
【问题描述】:
interface Info<
  BodyType = undefined,
  QueryStringType = undefined,
  PathParamType = undefined,
  ResponseType = undefined
> {
  request: {
    queryStrings: QueryStringType;
    pathParameters: PathParamType;
    body: BodyType;
  };
  response: ResponseType;
}

type InfoExtend = Info<{ name: string }>;

const a1: InfoExtend = {
  request: {
    body: { name: "a" },
  },
};

我有一个Info 类型,它是描述端点的接口,InfoExtend 是端点实现的实际类型。

问题是,a1 有一个类型错误:

类型'{正文:{名称:字符串; }; }' 缺少来自类型 '{ queryStrings: undefined; 的以下属性。路径参数:未定义;正文:{名称:字符串; }; }':查询字符串,路径参数(2739)

我明白了,因为 queryStringspathParameters。不是可选的

问题是,我能否将bodyqueryStringspathParameters 与泛型关联,这样,如果我通过BodyType 泛型,那么bodyInfo.request.body 中,如果我不通过BodyType,那么Info.request应该没有任何错误,并且必须包含3个中的1个(body/queryString/pathParams)

Playground link:

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以解决这个问题,将缺少的字段设为optional

    interface Info<
      BodyType = undefined,
      QueryStringType = undefined,
      PathParamType = undefined,
      ResponseType = undefined
    > {
      request: {
        queryStrings?: QueryStringType;
        pathParameters?: PathParamType;
        body: BodyType;
      };
      response?: ResponseType;
    }
    
    type InfoExtend = Info<{ name: string }>;
    
    const a1: InfoExtend = {
      request: {
        body: { name: "a" },
      },
    };
    

    Playground link

    【讨论】:

    • 谢谢,但它们仍然存在于最终类型中,如果您键入 a1.request.,则会弹出 queryStrings,但如果我不通过它们的泛型,我不需要它们类型。当前的 TS 可以吗?
    • 但在某些时候你不需要queryStringpathParametersresponse吗?现在它们是可选字段,这意味着request 不需要它们。 (也许我误解了你的评论)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2017-04-28
    • 1970-01-01
    • 2021-06-26
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多