类型'this'的参数不能分配给参数'Construct'

时间:2019-12-17 20:31:49

标签: node.js aws-cdk

我试图将lambda函数调用到“示例应用”堆栈中,这给我一个错误,因为我试图将其传递给参数“ this”。

这是我的lambda函数

export async function handler(event) {
    console.log("request:", JSON.stringify(event, undefined, 2));
    return {
        statusCode: 200,
        headers: { "Content-Type": "text/plain" },
        body: `Hello, CDK! You've hit ${event.path}\n`
    };
};

这是调用该函数的“ app”

//import sns = require('@aws-cdk/aws-sns');
//import subs = require('@aws-cdk/aws-sns-subscriptions');
//import sqs = require('@aws-cdk/aws-sqs');
import cdk = require('@aws-cdk/core');
import lambda = require('@aws-cdk/aws-lambda');

//Exports class from other file much like a function

export class CdkWorkshopStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { 
    super(scope, id, props);

    // Describes an AWSLambda Resource
    const hello = new lambda.Function (this, 'HelloHandler', {
      runtime: lambda.Runtime.NODEJS_8_10,    //execution environment
      code: lambda.Code.asset('lambda'),   // code loaded from the "lambda" directory
      handler: 'hello.handler'                // file is "hello", function is "handler"
    });
  }
}

我得到的错误是:


lib/cdk-workshop-stack.ts:31:39 - error TS2345: Argument of type 'this' is not assignable to parameter of type 'Construct'.
  Type 'CdkWorkshopStack' is not assignable to type 'Construct'.
    Types of property 'node' are incompatible.
      Type 'import("/Users/aroe/cdk-workshop/node_modules/@aws-cdk/core/lib/construct").ConstructNode' is not assignable to type 'import("/Users/aroe/cdk-workshop/node_modules/@aws-cdk/aws-lambda/node_modules/@aws-cdk/core/lib/construct").ConstructNode'.
        Types have separate declarations of a private property 'host'.

31     const hello = new lambda.Function(this, 'HelloHandler', {
                                         ~~~~

[1:24:08 PM] Found 1 error. Watching for file changes.

最后我正在使用Node版本v13.3.0

3 个答案:

答案 0 :(得分:2)

我遇到了相同的错误,因为@aws-cdk/aws-lambda@aws-cdk/aws-sns-subscriptions的安装版本不同,

aws-sns-subscriptions依赖于相同版本的aws-lambda

enter image description here

当我将@aws-cdk/aws-lambda版本降级时,错误消失了!

您还可以将所有aws-cdk软件包更新为相同版本。

答案 1 :(得分:0)

构造定义对我来说似乎正确。如果各个cdk模块的版本都不相同,则可能会发生该错误。有关示例,请参见enter link description here。尝试运行npm update;看看是否能解决问题。

答案 2 :(得分:0)

这可以通过简单地忽略“ this”错误并始终运行lambda来解决。我不相信如果它是一个实际的node / JS程序,它就不会奏效。但是,当使用CDK本机TypeScript时,它会让您大吃一惊。