简体   繁体   English

使用 Object.defineProperty 时,类型中缺少属性,但类型中需要属性

[英]Property is missing in type but required in type when using Object.defineProperty

I have this validation middleware that I'm trying to write to validate an empty payload when sending requests:我有这个验证中间件,我正在尝试编写它以在发送请求时验证空有效负载:

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

But when I come to use the middleware function:但是当我开始使用中间件 function 时:

validateRequestBody(myPostFunction, [isMissing]);

I get a TypeScript error on isMissing stating我在isMissing声明中收到 TypeScript 错误

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

Can anyone help me resolve this?谁能帮我解决这个问题? I couldn't really find any similar problems and would appreciate any help.我真的找不到任何类似的问题,并希望得到任何帮助。

Thank you!谢谢!

The type of isMissing (which comes from _isMissing ) is (body: any) => boolean (a function accepting a single parameter of type any and returning a boolean ), but ValidationFunction requires an _apiGatewayResponse property on it. The type of isMissing (which comes from _isMissing ) is (body: any) => boolean (a function accepting a single parameter of type any and returning a boolean ), but ValidationFunction requires an _apiGatewayResponse property on it. Even though you add the property at runtime via Object.defineProperty , that doesn't change the compile-time type that the function has.即使您在运行时通过Object.defineProperty添加属性,也不会更改 function 具有的编译时类型。

You can assure TypeScript that the result has the right type via an innocuous type assertion that only asserts what you can easily see the code is adding.您可以通过一个无害的类型断言向 TypeScript 保证结果具有正确的类型,该断言仅断言您可以轻松看到代码正在添加的内容。 For example:例如:

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 游乐场链接

You could just use as IsMissingFunction instead of the more long-winded as typeof _isMissing & Pick<ValidationFunction, "_apiGatewayResponse"> :可以只使用as IsMissingFunction而不是更冗长的as typeof _isMissing & Pick<ValidationFunction, "_apiGatewayResponse">

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

The reason I prefer the first version is that if you edit IsMissingFunction (or ValidationFunction ) later to add more properties, TypeScript will raise a helpful error on the first example indicating that the function no longer fits the definition of IsMissingFunction .我更喜欢第一个版本的原因是,如果您稍后编辑IsMissingFunction (或ValidationFunction )以添加更多属性,TypeScript 将在第一个示例中引发一个有用的错误,表明 function 不再符合IsMissingFunction的定义。 With the second example, you'd have to make a really big change for it to complain.对于第二个示例,您必须进行非常大的更改才能使其抱怨。

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

相关问题 使用Object.defineProperty动态创建的类型检查属性 - Type-checking properties created dynamically with Object.defineProperty 打字稿:通过`Object.defineProperty`向数组类型添加别名 - Typescript: adding aliases via `Object.defineProperty` to an array type 类型中缺少属性,但它是必需的 - Property missing in type but it is required 对对象的角度HttpParams,Object.defineProperty创建属性,但超出范围 - Angular HttpParams to object, Object.defineProperty creates property but is out of scope 类型中缺少属性,但类型中需要属性 - Property is missing in type but required in type 为什么我的属性在装饰器中的 Object.defineProperty 之后消失了? - Why does my property disapear after Object.defineProperty in decorator? 使用Object.defineProperty后如何读取typescript中的属性? - How to read properties in typescript after using Object.defineProperty? 类型中缺少属性“类型”。但类型“道具”中是必需的 - Property 'type' is missing in type .but required in type 'Props' “{}”类型中缺少属性“filteredUsers”,但在“Props”类型中是必需的 - Property 'filteredUsers' is missing in type '{}' but required in type 'Props' 类型“{}”中缺少属性“className”,但类型“IProps”需要 - Property 'className' is missing in type '{}' but required in type 'IProps'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM