【问题标题】:Declaration merging for asseting non-null资产非空的声明合并
【发布时间】:2021-05-24 07:25:19
【问题描述】:

我想对 @types/aws-lambda 进行调整,以表达我们的意图,即 pathParameters 不为空并且具有特定格式。

export interface APIGatewayProxyEventBase<TAuthorizerContext> {
    body: string | null;
    headers: APIGatewayProxyEventHeaders;
    multiValueHeaders: APIGatewayProxyEventMultiValueHeaders;
    httpMethod: string;
    isBase64Encoded: boolean;
    path: string;
    pathParameters: APIGatewayProxyEventPathParameters | null;
    // ...snip...
}
export interface APIGatewayProxyEventPathParameters {
    [name: string]: string | undefined;
}

在我们的应用程序代码中,我们可以表示 fooId 不为空

declare module "aws-lambda/trigger/api-gateway-proxy" {
  export interface APIGatewayProxyEventPathParameters {
    fooId: string;
  }
}

export const handler: APIGatewayProxyHandler = async (event) => {
  // This is still needed
  if (!event.pathParameters) {
    throw new Error("parameter is empty");
  }
  // Without declaration merging, fooId is string | undefined 
  // but is now string
  const { fooId } = event.pathParameters;

为了删除if (!event.pathParameters),我写了这个:

declare module "aws-lambda/trigger/api-gateway-proxy" {
  export interface APIGatewayProxyEventBase<T> {
    pathParameters: APIGatewayProxyEventPathParameters;
  }
  export interface APIGatewayProxyEventPathParameters {
    fooId: string
  }
}

并给出以下错误。

error TS2428: All declarations of 'APIGatewayProxyEventBase' must have identical type parameters.
error TS2717: Subsequent property declarations must have the same type.  Property 'pathParameters' must be of type 'APIGatewayProxyEventPathParameters | null', but here has type 'APIGatewayProxyEventPathParameters'.

event 可以是 { pathParameters: { fooId: string }, ... } 类型而不是 { pathParameters?: { fooId: string }, ... } 吗?

【问题讨论】:

  • 声明合并不允许对合并类型进行任意修改...对于这样的事情,您可能只想提供您自己的相关库类型版本,而不是导入原始类型.不知道有没有人有更好的答案...

标签: typescript aws-lambda typescript-typings


【解决方案1】:

您可以使用Omit utility type 来完成此操作。

interface LambdaEvent extends Omit<APIGatewayProxyEventV2, 'pathParameters'> {
  pathParameters: { fooId: string }
}

然后使用修改后的LambdaEvent 类型在您的处理程序中键入事件参数

export const handler: Handler<LambdaEvent, APIGatewayProxyResultV2> = (event) => { ... }

这在处理程序类型file 中有示例

【讨论】:

  • 我想type APIGatewayProxyHandler = Handler&lt;APIGatewayProxyEvent, APIGatewayProxyResult&gt;; 自动与调整后的APIGatewayProxyEventBase 一起工作。这可能吗?
  • 我不确定您所说的自动是什么意思。你能详细说明吗?您可以在此处查看类型是如何定义的,以了解如何修改/使用它们 - github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/…
  • @yskkin 我添加了一个指向类型文件的链接,其中记录了这种方法的示例。如果我可以提供任何其他信息以使该答案被接受,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2016-02-18
  • 2018-03-05
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多