Home > Back-end >  How to read arrow function type definition in typescript
How to read arrow function type definition in typescript

Time:07-16

When I try to develop my app by serverless-framework

Now I stuck in typescript specific issues.

my question is const hello: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (event) =>.

so hello function is defined. but what is ValidatedEventAPIGatewayProxyEvent ?

it defined return type? or input value type ?

How can I read them correctly?

I searched about them but I couldn't find ts document about it. if someone has opinion of materials will you please let me know. Thanks

handler.ts

import type { ValidatedEventAPIGatewayProxyEvent } from '@libs/api-gateway';
import { formatJSONResponse } from '@libs/api-gateway';
import { middyfy } from '@libs/lambda';

import schema from './schema';

const hello: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (event) => {
  return formatJSONResponse({
    message: `Hello ${event.body.name}, welcome to the exciting Serverless world!`,
    event,
  });
};

export const main = middyfy(hello);

schema.ts

export default {
  type: "object",
  properties: {
    name: { type: 'string' }
  },
  required: ['name']
} as const;

api-gateway.ts

import type { APIGatewayProxyEvent, APIGatewayProxyResult, Handler } from "aws-lambda"
import type { FromSchema } from "json-schema-to-ts";

type ValidatedAPIGatewayProxyEvent<S> = Omit<APIGatewayProxyEvent, 'body'> & { body: FromSchema<S> }
export type ValidatedEventAPIGatewayProxyEvent<S> = Handler<ValidatedAPIGatewayProxyEvent<S>, APIGatewayProxyResult>

export const formatJSONResponse = (response: Record<string, unknown>) => {
  return {
    statusCode: 200,
    body: JSON.stringify(response)
  }
}

CodePudding user response:

If you write const test:number = 1 typescript assumes that test is of type number. In your case it defines the type of the arrow function not return type.

Like this example: const test:(e:unknown) => number = (e:unknown) => 1

This type after the colon defines that the arrow method has one argument of type unknown and returns a number.

Serverless Framework provides types for all of their methods that you handler matches the definition of their type.

  • Related