【问题标题】:Property is missing in type but required in type when using Object.defineProperty使用 Object.defineProperty 时,类型中缺少属性,但类型中需要属性
【发布时间】:2022-01-19 19:22:21
【问题描述】:

我有这个验证中间件,我正在尝试编写它以在发送请求时验证空有效负载:

const _isMissing = (body: any): boolean => !body;

export const isMissing = Object.defineProperty(_isMissing, '_apiGatewayResponse', {
  value: LAMBDA_400_RESPONSE,
});

interface ValidationFunction extends Function {
  _apiGatewayResponse: APIGatewayProxyResult;
}

export function validateRequestBody(
  handler: LambdaFunction,
  validations: Array<ValidationFunction>,
): LambdaFunction {
  const wrapper: LambdaFunction = async (
    event: APIGatewayEvent,
  ): Promise<APIGatewayProxyResult> => {
    const eventBody = event.body ? JSON.parse(event.body) : null;
    for (const validation of validations) {
      const invalidBody = validation(eventBody);
      if (invalidBody) {
        return validation._apiGatewayResponse || LAMBDA_400_RESPONSE;
      }
    }

    const response = await handler(event);
    return response;
  };

  return wrapper;
}

但是当我开始使用中间件功能时:

validateRequestBody(myPostFunction, [isMissing]);

我在isMissing 声明中收到 TypeScript 错误

Property '_apiGatewayResponse' is missing in type '(body: any) =&gt; boolean' but required in type 'ValidationFunction'.

谁能帮我解决这个问题?我真的找不到任何类似的问题,希望能得到任何帮助。

谢谢!

【问题讨论】:

    标签: typescript defineproperty


    【解决方案1】:

    isMissing(来自_isMissing)的类型是(body: any) =&gt; boolean(接受any 类型的单个参数并返回boolean 的函数),但ValidationFunction 需要_apiGatewayResponse财产。即使您在运行时通过Object.defineProperty 添加属性,也不会更改函数具有的编译时类型。

    您可以通过无害的类型断言向 TypeScript 保证结果具有正确的类型,该断言仅断言您可以轻松看到代码正在添加的内容。例如:

    type IsMissingFunction = ((body: any) => boolean) & ValidationFunction;
    
    const _isMissing = (body: any): boolean => !body;
    
    export const isMissing: IsMissingFunction = Object.defineProperty(
        _isMissing as typeof _isMissing & Pick<ValidationFunction, "_apiGatewayResponse">,
        '_apiGatewayResponse', {
            value: LAMBDA_400_RESPONSE
        }
    );
    

    Playground link

    可以只使用as IsMissingFunction而不是更冗长的as typeof _isMissing &amp; Pick&lt;ValidationFunction, "_apiGatewayResponse"&gt;

    type IsMissingFunction = ((body: any) => boolean) & ValidationFunction;
    
    const _isMissing = (body: any): boolean => !body;
    
    export const isMissing: IsMissingFunction = Object.defineProperty(
        _isMissing as IsMissingFunction,
        '_apiGatewayResponse', {
            value: LAMBDA_400_RESPONSE
        }
    );
    

    我更喜欢第一个版本的原因是,如果您稍后编辑IsMissingFunction(或ValidationFunction)以添加更多属性,TypeScript 将在第一个示例中引发一个有用的错误,表明该函数不再符合IsMissingFunction。对于第二个示例,您必须进行真正大的更改才能使其抱怨。

    【讨论】:

    • 非常感谢!事情就这么清楚了。感谢您的帮助和详细解释:)
    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2020-05-30
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2021-07-29
    相关资源
    最近更新 更多