Search code examples
typescriptaws-lambdaserverless

Fixing serverless typescript, Types of property 'event' are incompatible?


I've upgraded to serverless 3, running typescript. There is a type match error in the serverless configuration files since.

Partially my serverless.ts file is

const serverlessConfiguration: Serverless = {
service: 'hello',
frameworkVersion: '3',
useDotenv: true,

plugins: ['serverless-webpack', 'serverless-domain-manager', 'serverless-iam-roles-per-function', 'serverless-certificate-creator'],
provider: {
    name: 'aws',
    runtime: 'nodejs14.x',
    region: 'ap-southeast-2',
    apiGateway: {
        minimumCompressionSize: 1024,
        shouldStartNameWithService: true,
    },
    environment: {
        AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
    },
},
functions: {hello},
custom: {

There is something wrong with the schema of hello/index.ts file is

import schema from './schema';
import { handlerPath } from '@libs/handlerResolver';

export default {
  handler: `${handlerPath(__dirname)}/handler.main`,
  events: [
   {
     http: {
       method: 'post',
       path: 'hello',
       private: false,
       request: {
         schemas: {
           'application/json': schema
        }
      }
    }
  }
 ]

}

I've read that http.request.schema has been replaced by http.request.schemas

The error message I'm getting is

  Type '{ schemas: { 'application/json': { readonly type: "object"; readonly properties: { readonly name: { readonly type: "string"; }; }; readonly required: readonly ["name"]; }; }; }' has no properties in common with type 'HttpRequestValidation'.

Solution

  • The package @types/serverless has the wrong specification

    Remove this package

    npm remove @types/serverless 
    

    Add the serverless typescript package

    npm i -D @serverless/typescript
    

    Change the import in serverless.ts from

    import type {Serverless} from 'serverless/aws';
    

    to

    import type {AWS} from "@serverless/typescript";
    

    Make sure that index.ts has scheams and not schema.

    The final index.ts file is as above

    Ref