Argument of type 'App' is not assignable to parameter of type 'Construct'

Viewed 5085

I am trying simple CDK tutorial, however I bumped into some error.

My code is simply like this,

Argument of type 'App' is not assignable to parameter of type 'Construct'.
Type 'App' is missing the following properties from type 'Construct': onValidate, onPrepare, onSynthesize, validate, and 2 more.

7 new HelloCdkStack(app, 'HelloCdkStack', {

Somehow this error comes, but in a few tutorials using cdk.App(). Why does this error happens??

import * as cdk from "@aws-cdk/core";
import {Table, AttributeType} from "@aws-cdk/aws-dynamodb";

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

    new Table(this, "items", {
      partitionKey: {
        name: "itemId",
        type: AttributeType.STRING,
      },
      tableName: "items",
      removalPolicy: cdk.RemovalPolicy.DESTROY, // NOT recommended for production code
    });
    // The code that defines your stack goes here

    // example resource
    // const queue = new sqs.Queue(this, 'HelloCdkQueue', {
    //   visibilityTimeout: cdk.Duration.seconds(300)
    // });
  }
}
const app = new cdk.App();
new HelloCdkStack(app, "HelloCdkStack");
app.synth();
2 Answers

In AWS CDK 1.x, imports were done using import were made from '@aws-cdk/core'. This was changed in CDK 2.x, in which imports are made from aws-cdk-lib package.

Many tutorials would still use CDK 1.x whereas starter code for CDK uses 2.x. This is why you have discrepancy because the code for App initialization would say use the newer module whereas the tutorials would assume you'd do this the old way.

To fix this,

  1. update your stack file to use the new one: import { Stack, StackProps } from 'aws-cdk-lib';
  2. update your app initialization file to use old one: import * as cdk from '@aws-cdk/core';

Documentation for AWS CDK 2.x: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html

Documentation for AWS CDK 1.x: https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html

Go to the cdk_primer-stack.ts file and fix the import of your core SDK from import * as cdk from 'aws-cdk-lib'; to import * as cdk from '@aws-cdk/core'; The problem is that you are using a different version of CDK Core in your file than imported in cdk_primer-stack.ts.

Related