Running into an error while going thru a tutorial on AWS CDK. The constructor S3.Bucket expects a construct but the class that extends cdk.Stack doesn't appear to implement Construct. It does extend the CoreConstruct. Not sure how the Construct and CoreConstruct are related. Below is the source code and the 'this' in line const bucket = new s3.Bucket(**this**, "SampleBucket", {
throws the error.
import * as cdk from "@aws-cdk/core";
import * as s3 from "aws-cdk-lib/aws-s3";
export class CdkSampleStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const bucket = new s3.Bucket(this, "SampleBucket", {
encryption: s3.BucketEncryption.S3_MANAGED,
});
const output = new cdk.CfnOutput(this, "SampleBucketNameExport", {
value: bucket.bucketName,
exportName: "SampleBucketName",
});
console.log(output);
}
}
The error is:
Argument of type 'this' is not assignable to parameter of type 'Construct'.
Type 'CdkSampleStack' is not assignable to type 'Construct'.
Types of property 'node' are incompatible.
Type 'ConstructNode' is missing the following properties from type 'Node': _locked, _children, _context, _metadata, and 6 more.ts(2345)
Any idea what's wrong?
Thanks in advance for your help.
CodePudding user response:
So your problem is you are mixing versions here. aws-cdk-lib
is the v2 of the AWS CDK. The @aws-cdk/*
libraries like @aws-cdk/core
are v1 versions of the library. So in your example, you should just remove the dependency on @aws-cdk/core
and instead you can import everything from aws-cdk-lib
, IE
// The top level namespace includes all stuff that used to be in `@aws-cdk/core`, see the docs here https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib-readme.html
import * as cdk from "aws-cdk-lib";
import * as s3 from "aws-cdk-lib/aws-s3";
// v2 no longer wraps the interface with it's own thing so just use `constructs.Construct` directly
import { Constructs } from 'constructs';
export class CdkSampleStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const bucket = new s3.Bucket(this, "SampleBucket", {
encryption: s3.BucketEncryption.S3_MANAGED,
});
const output = new cdk.CfnOutput(this, "SampleBucketNameExport", {
value: bucket.bucketName,
exportName: "SampleBucketName",
});
console.log(output);
}
}