AWS CDKのArgument of type 'this' is not assignable to parameter of type 'Construct'エラーの対応方法
AWS CDK 1.15.0 がリリースされました!
https://github.com/aws/aws-cdk/releases/tag/v1.15.0
アップデート前に作業していたCDKプロジェクトで、新しくリソースを追加したところ、以下のエラーが発生しました。
Argument of type 'this' is not assignable to parameter of type 'Construct'.
コード
import cdk = require('@aws-cdk/core'); import sns = require('@aws-cdk/aws-sns'); import subs = require('@aws-cdk/aws-sns-subscriptions'); // 1.15.0 リリース後に追加 import lambda = require('@aws-cdk/aws-lambda'); import events = require('@aws-cdk/aws-events'); import targets = require('@aws-cdk/aws-events-targets'); export class HogeStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // SNSトピック const topic = new sns.Topic(this, 'HogeTopic'); topic.addSubscription(new subs.EmailSubscription('hoge@hoge.hoge')); // Lambda関数 (第1引数のthisで今回のエラーが発生している) const lambdaFn = new lambda.Function(this, 'HogeFunction', { code: lambda.Code.asset('lambda/dist'), handler: 'lambda_function.lambda_handler', runtime: lambda.Runtime.PYTHON_3_7, timeout: cdk.Duration.seconds(300), environment: { topic: topic.topicArn } }); // Cloud Watch Events (第1引数のthisで今回のエラーが発生している) const rule = new events.Rule(this, 'Rule', { schedule: events.Schedule.expression('cron(30 6 * * ? *)'), }); rule.addTarget(new targets.LambdaFunction(lambdaFn)); } }
対応方法
package.jsonのバージョン情報を修正します。
{ ... "dependencies": { "@aws-cdk/aws-events": "^1.15.0", "@aws-cdk/aws-events-targets": "^1.15.0", "@aws-cdk/aws-lambda": "^1.15.0", # 新しく追加したCDKリソースのバージョンに合わせる(1.14.0 -> 1.15.0) "@aws-cdk/aws-sns": "^1.15.0", "@aws-cdk/aws-sns-subscriptions": "^1.15.0", "@aws-cdk/core": "^1.15.0", "source-map-support": "^0.5.9" } ... }
node_modulesディレクトリを削除し、再度インストールします。
rm -rf node_modules npm run install