【发布时间】: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