aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code

Home Page:https://aws.amazon.com/cdk

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TS - Argument of type 'this' is not assignable to parameter of type 'Construct'

Deepakkothandan opened this issue · comments

I have a created a simple Stack that creates a VPC with three simple subnets. though I receive the error Argument of type 'this' is not assignable to parameter of type 'Construct' . When I use any other resource like S3 or SQS I do not receive the error. As of now, it happens only with VpcNetwork. The typescript code is as follows

cdk version: 0.8.0 (build bb95676)
node version: 10.3.0

import * as cdk from '@aws-cdk/cdk'
import { VpcNetwork, SubnetType } from '@aws-cdk/aws-ec2'

class MyStack extends cdk.Stack {
    constructor(parent: cdk.App, name: string, props?: cdk.StackProps) {
        super(parent, name, props);

        new VpcNetwork(this, 'MyVPC', {
            cidr: '10.0.0.0/21',
            subnetConfiguration: [
              {
                cidrMask: 24,
                name: 'Ingress',
                subnetType: SubnetType.Public,
                natGateway: true,
              },
              {
                cidrMask: 24,
                name: 'Application',
                subnetType: SubnetType.Private,
              },
              {
                cidrMask: 28,
                name: 'Database',
                subnetType: SubnetType.Isolated,
              }
            ],
        });
    }
}

const app = new cdk.App(process.argv);
new MyStack(app, 'MyStack');
process.stdout.write(app.run());

This doesn't repro in 0.8.1, do you mind upgrading to the latest version and trying again? Let us know if you still encounter issues.

P.S. the natGateway property is not needed anymore...

@eladb works after upgrading to 0.8.1 . Thanks

I'm experiencing this problem too using 0.20.0. I was following the example found here

https://awslabs.github.io/aws-cdk/examples.html#step-3-create-a-fargate-service

and received a similar error to the one described above

# ~/Sites/playground/cdk-example  master npm run build

> cdk-example@0.1.0 build /Users/benswinburne/Sites/playground/cdk-example
> tsc

lib/cdk-example-stack.ts:10:36 - error TS2345: Argument of type 'this' is not assignable to parameter of type 'Construct'.
  Property '_escapePathSeparator' is missing in type 'CdkExampleStack' but required in type 'Construct'.

10     const vpc = new ec2.VpcNetwork(this, 'MyVpc', {
                                      ~~~~

  node_modules/@aws-cdk/aws-ec2/node_modules/@aws-cdk/cdk/lib/core/construct.d.ts:205:13
    205     private _escapePathSeparator;
                    ~~~~~~~~~~~~~~~~~~~~
    '_escapePathSeparator' is declared here.

lib/cdk-example-stack.ts:14:37 - error TS2345: Argument of type 'this' is not assignable to parameter of type 'Construct'.

14     const cluster = new ecs.Cluster(this, 'MyCluster', {
                                       ~~~~

lib/cdk-example-stack.ts:19:40 - error TS2345: Argument of type 'this' is not assignable to parameter of type 'Construct'.

19     new ecs.LoadBalancedFargateService(this, 'MyFargateService', {
                                          ~~~~


Found 3 errors.

I've pushed the example to a repo exactly as I have it

npm -v
6.4.1
node -v
v8.12.0

https://github.com/benswinburne/cdk-example

Hi @benswinburne, I believe this is caused by the fact that your package.json file has mixed versions of the CDK (@aws-cdk/cdk is at 0.20.0 and @aws-cdk/aws-* are at 0.21.0):

{
  "dependencies": {
    "@aws-cdk/aws-ec2": "^0.21.0",
    "@aws-cdk/aws-ecs": "^0.21.0",
    "@aws-cdk/cdk": "^0.20.0"
  }
}

Try to upgrade everything to 0.21.0 and let us know if the issue still persists.

I'm getting this same error while working through the AWS CDK Workshop.
Argument of type 'this' is not assignable to parameter of type 'Construct'.
Type 'HitCounter' is not assignable to type 'Construct'.
Types of property 'node' are incompatible.
Type 'import("/Users/dev_user/code/aws/cdk/cdk-workshop/node_modules/@aws-cdk/core/lib/construct").ConstructNode' is not assignable to type
'import("/Users/dev_user/code/aws/cdk/cdk-workshop/node_modules/@aws-cdk/aws-dynamodb/node_modules/@aws-cdk/core/lib/construct").ConstructNode'.
Types have separate declarations of a private property 'host'.ts(2345)

Following is the package.json
{
"name": "cdk-workshop",
"version": "0.1.0",
"bin": {
"cdk-workshop": "bin/cdk-workshop.js"
},
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"cdk": "cdk"
},
"devDependencies": {
"@types/node": "8.10.45",
"typescript": "^3.3.3333",
"ts-node": "^8.1.0",
"aws-cdk": "^1.0.0"
},
"dependencies": {
"@aws-cdk/aws-apigateway": "^1.0.0",
"@aws-cdk/aws-dynamodb": "^1.1.0",
"@aws-cdk/aws-lambda": "^1.0.0",
"@aws-cdk/aws-sns": "^1.0.0",
"@aws-cdk/aws-sns-subscriptions": "^1.0.0",
"@aws-cdk/aws-sqs": "^1.0.0",
"@aws-cdk/core": "^1.0.0"
}
}

The type seems to be specified properly. This seems to be a bug.

commented

I'm getting this same error while working through the AWS CDK Workshop.
Argument of type 'this' is not assignable to parameter of type 'Construct'.
Type 'HitCounter' is not assignable to type 'Construct'.
Types of property 'node' are incompatible.
Type 'import("/Users/dev_user/code/aws/cdk/cdk-workshop/node_modules/@aws-cdk/core/lib/construct").ConstructNode' is not assignable to type
'import("/Users/dev_user/code/aws/cdk/cdk-workshop/node_modules/@aws-cdk/aws-dynamodb/node_modules/@aws-cdk/core/lib/construct").ConstructNode'.
Types have separate declarations of a private property 'host'.ts(2345)

Following is the package.json
{
"name": "cdk-workshop",
"version": "0.1.0",
"bin": {
"cdk-workshop": "bin/cdk-workshop.js"
},
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"cdk": "cdk"
},
"devDependencies": {
"@types/node": "8.10.45",
"typescript": "^3.3.3333",
"ts-node": "^8.1.0",
"aws-cdk": "^1.0.0"
},
"dependencies": {
"@aws-cdk/aws-apigateway": "^1.0.0",
"@aws-cdk/aws-dynamodb": "^1.1.0",
"@aws-cdk/aws-lambda": "^1.0.0",
"@aws-cdk/aws-sns": "^1.0.0",
"@aws-cdk/aws-sns-subscriptions": "^1.0.0",
"@aws-cdk/aws-sqs": "^1.0.0",
"@aws-cdk/core": "^1.0.0"
}
}

The type seems to be specified properly. This seems to be a bug.

Same error here

Me too, the error comes up on a super minimal:

new Queue(this, 'foo')

Exact some error

Argument of type 'this' is not assignable to parameter of type 'Construct'.
...
Types have separate declarations of a private property 'host'

As mentioned above, this is usually caused by having more than a single version of the CDK in your node modules.

  1. Make sure your package.json lists the same version.
  2. Nuke node_modules
  3. Run npm install again

Yeah, this was the issue. I did the init yesterday, and installed packages today, so they were mismatched:

aws-cdk=1.6.0,@aws-cdk/core=1.5.0 and this was causing the issue.

It'd be really great since this seems like a common issue for people that we had a nicer error message here, perhaps the cdk command could verify that dependencies are in sync since they appear to have hard dependencies on being the exact same versions?

The error was not obvious, and this thread didn't really help solve it, since the packages being mismatched was never discussed here, just someone upgrading from one version to the next solved it. This issue was the one that made me double check and upgrade all versions: #3416

It's a good idea but might be a bit tricky for us to handle at the CLI level because it is language agnostic. We are actually changing the way peer dependencies are defined (see #3783) so I hope that this will improve the experience a little.

At any rate, you are right. This is an annoying friction we are aware of and would look into ways to improve this experience.

You should absolutely re-open this issue as this clearly has not been adequately solved. We've incurred a lot of cost trying to wrangle between version mismatches and I'm not even sure that fully diagnoses the issue of something as trivial as two separate versions of the Construct class.

This amounts to "configuration hell" and the responsible thing is to own that these issues exist or clearly state your assumptions in your documentation about what developers need to do to circumvent such issues in reliable ways. As of now, my conclusion is that building CDK applications in TypeScript is a waste of time (prefer JavaScript).

commented

Yeah, this was the issue. I did the init yesterday, and installed packages today, so they were mismatched:

aws-cdk=1.6.0,@aws-cdk/core=1.5.0 and this was causing the issue.

It'd be really great since this seems like a common issue for people that we had a nicer error message here, perhaps the cdk command could verify that dependencies are in sync since they appear to have hard dependencies on being the exact same versions?

The error was not obvious, and this thread didn't really help solve it, since the packages being mismatched was never discussed here, just someone upgrading from one version to the next solved it. This issue was the one that made me double check and upgrade all versions: #3416

I have similar issue. I did cdk init then after few hours did npm install @aws-cdk/aws-ec2.
I realized that the problem is caused by different versions:

    "@aws-cdk/aws-ec2": "^1.32.2",
    "@aws-cdk/core": "1.32.1",

Just after few hours there is a minor update on the module. Problem solved by changing aws-cdk/core version to 1.32.2

Since I stumpled over this one, even in latest cdk:

  1. How to debug:

In working state, get the output of code that is a result of synth

CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Modules: aws-cdk=1.32.0,@aws-cdk/aws-cloudwatch=1.32.2,@aws-cdk/aws-ec2=1.32.2,@aws-cdk/aws-events=1.32.2,@aws-cdk/aws-iam=1.32.2,@aws-cdk/aws-kms=1.32.2,@aws-cdk/aws-logs=1.32.2,@aws-cdk/aws-s3=1.32.2,@aws-cdk/aws-ssm=1.32.2,@aws-cdk/core=1.32.2,@aws-cdk/cx-api=1.32.2,@aws-cdk/region-info=1.32.2,jsii-runtime=node.js/v10.16.3

Aws CDK has a mismatch (1.32.0) to the other modules (1.32.2).

  1. You might want to fix this, by not using the circumflex '^' in your package.json.

you might not only want to nuke your node_modules folder, but as well the package-lock.json

This is a little side effect of the way typings work and how they evolve. An argument could be made, that a minor update is not the right thing as soon as a typing changed.

I hope this helps if you stumble over this problem.

@sebsonjura thanks for the fix. AWS documentation perhaps needs to mention this explicitly as it is not in the typescript workshop. It would be useful. Thanks again!

Just to add, for anyone still struggling even after the helpful comments above:

After you nuke node_modules and package-lock.json, you then have to change all the versions for cdk things in package.json UP TO THE NEW VERSION, not down to old one. I tried changing it down (since I'd prefer not to be forced to use the latest minor release within minutes of it being released) and that didn't work. Upwards and onwards.

Maybe a version mismatch check could be added to cdk doctor?

I updated all my dependencies to 1.55 and it worked like a charm!

Please try to use 1.56.0 without the ^ whenever using CDK.

Also your devDependency links to 1.45.0

I'm getting this error, and I only have one instance of the @aws-cdk in my dependencies, and no carets. I tried deleting the node_modules folder and package-lock.json as well, to no avail.

"dependencies": {
"@aws-cdk/aws-ssm": "1.88.0",
"@types/aws-lambda": "8.10.71",
"@types/node": "14.14.25",
"axios": "0.21.1"
},
...
"devDependencies": {"chai": "4.2.0",
"mocha": "8.2.1",
"typescript": "3.8.3"

....

**src-ts/app.ts:39:85 - error TS2345: Argument of type 'typeof globalThis' is not assignable to parameter of type 'Construct'.
Type 'typeof globalThis' is missing the following properties from type 'Construct': onValidate, onPrepare, onSynthesize

39 const secureStringToken = ssm.StringParameter.valueForSecureStringParameter(this, stringSecretKey, secretVersion);**

I had exactly the same issue with Python Function, I will share my workaround on this.

Write

const python_lambda = require ('@aws-cdk/aws-lambda-python')

Instead of

import * as python_lambda from '@aws-cdk/aws-lambda-python

And then declare your object

    const Lambda = new python_lambda.PythonFunction(this, 'MyFunction', {
      entry: path.join(__dirname, '../lambda'), // required
      index: 'index.py'
      handler: 'lambda_handler', 
      runtime: lambda.Runtime.PYTHON_3_8, 
    });

Same issue as well, after updating CDK packages to latest. I have mismatch since not all packages are available in NPM as latest version -- is this expected behavior that we can only upgrade to the latest version that is in common with all used CDK packages?

same here, had to downgrade from "aws-sdk": "^2.880.0" to "aws-sdk": "^2.879.0" in order to fix it.

In my case it was just a problem with cached types. If you are working in typescript VSCode, try restarting it.

Could somebody tell me what's the issue here?

  "devDependencies": {
    "@types/jest": "^26.0.10",
    "@types/node": "10.17.27",
    "jest": "^26.4.2",
    "ts-jest": "^26.2.0",
    "aws-cdk": "2.12.0",
    "ts-node": "^9.0.0",
    "typescript": "~3.9.7"
  },
  "dependencies": {
    "@aws-cdk/aws-elasticbeanstalk": "^1.144.0",
    "@aws-cdk/aws-iam": "^1.144.0",
    "aws-cdk-lib": "2.12.0",
    "constructs": "^10.0.60",
    "source-map-support": "^0.5.16"
  }

A fresh new project just minutes ago, and I keep getting these errors:

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

@omar-dulaimi you're mixing CDK v1 ("@aws-cdk/aws-elasticbeanstalk" and "@aws-cdk/aws-iam") and CDK v2 ("aws-cdk-lib").

Get rid of the V1 dependencies, re-install your modules, and you should be good to go 🙂.

@skinny85 Thanks. I was following some tutorials. It would have been better if the library showed a warning about this. It's confusing for new users.

Agreed @omar-dulaimi. The problem is it's tricky to do dependency-related detection (we are another dependency in your closure, after all).

@skinny85

Get rid of the V1 dependencies, re-install your modules, and you should be good to go 🙂.

By removing all V1 deps then I only have aws-cdk-lib. What about all those import stuff from both modules in the lib folder?

@jordiyapz Maybe there's a better way, but this is how I did it:

import {
  Stack,
  StackProps,
  aws_elasticbeanstalk as elasticbeanstalk,
  aws_iam as iam,
  aws_ec2 as ec2,
  aws_rds as rds,
  aws_s3 as s3,
  aws_ecr as ecr,
  RemovalPolicy,
  Duration,
} from "aws-cdk-lib";

Ohh waw, they combine multiple modules into one 😯. Thanks @omar-dulaimi , I'll try it. Anw, currently the aws documentation site (docs.aws.amazon.com) is unreachable so I have no way to lookup on how to use the V2 version of elasticbeanstalk module. Thanks again for the quick reply.

UPDATE: Yes, it worked! Thanks

following aws tutorial for creating vpc

import * as cdk from '@aws-cdk/core';
import { Vpc, SubnetType } from '@aws-cdk/aws-ec2';

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

    // The code that defines your stack goes here
    // CHANGE: We have created the vpc object from the Vpc class.
    const vpc = new Vpc(this, 'MainVpc',{
    
    // CHANGE: this is where we define how many AZs to use
    maxAzs: 2,
      
   // CHANGE: We define a single subnet configuration per AZ.
      subnetConfiguration:  [
        {
          // CHANGE: this is it's CIDR mask so 255.255.255.0
          cidrMask: 24,

          // CHANGE: a name for each of these subnets
          name: 'public-subnet',

          // CHANGE: and the subnet type to be used - here we will have
          // a public subnet. There are other options available here.
          subnetType: SubnetType.PUBLIC
        },
      ]
    });
  }
}

after run npm build I get the following error

bin/cdk-demo.ts:7:18 - error TS2345: 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.

I am learning . I think it might be relevant to this issue. can you please help me

I was having the same issue following a tutorial from AWS and the solution from @omar-dulaimi worked!

Basically change this:
import * as ec2 from "@aws-cdk/aws-ec2"; import * as ecs from "@aws-cdk/aws-ecs"; import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns";

To this:
import { Stack, StackProps, aws_ec2 as ec2, aws_ecs as ecs, aws_ecs_patterns as ecs_patterns } from 'aws-cdk-lib';

following aws tutorial for creating vpc

import * as cdk from '@aws-cdk/core';
import { Vpc, SubnetType } from '@aws-cdk/aws-ec2';

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

    // The code that defines your stack goes here
    // CHANGE: We have created the vpc object from the Vpc class.
    const vpc = new Vpc(this, 'MainVpc',{
    
    // CHANGE: this is where we define how many AZs to use
    maxAzs: 2,
      
   // CHANGE: We define a single subnet configuration per AZ.
      subnetConfiguration:  [
        {
          // CHANGE: this is it's CIDR mask so 255.255.255.0
          cidrMask: 24,

          // CHANGE: a name for each of these subnets
          name: 'public-subnet',

          // CHANGE: and the subnet type to be used - here we will have
          // a public subnet. There are other options available here.
          subnetType: SubnetType.PUBLIC
        },
      ]
    });
  }
}

after run npm build I get the following error

bin/cdk-demo.ts:7:18 - error TS2345: 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.

I am learning . I think it might be relevant to this issue. can you please help me

With regards to the tutorial of creating VPC in AWS, don't install the separate npm package for vpc and update your imports as suggested by @adrianmf94.

import {
  Stack,
  StackProps,
  aws_ec2 as ec2,
} from 'aws-cdk-lib';
import { Construct } from 'constructs';

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

    const vpc = new ec2.Vpc(this, 'MainVpc', {
      maxAzs: 2,
      subnetConfiguration: [
        {
          cidrMask: 24,
          name: 'public-subnet',
          subnetType: ec2.SubnetType.PUBLIC,
        },
      ],
    });
  }
}

commented

I'm just going through the AWS getting started tutorials:
https://aws.amazon.com/getting-started/guides/setup-cdk/module-three/
and I'm running into the same issue.
In my case the it seems the tutorial is written for the V1 libraries, while V2 is now the default install.
So following the tutorial results in trying to use V1 and V2 libraries at the same time.
I was able to fix it with some knowledge of JavaScript and some googling, and I figured how to use V2, but it's less than ideal.
I think the tutorial documents need updating to use V2 so that new people don't have to get so confused.

I'm just going through the AWS getting started tutorials: https://aws.amazon.com/getting-started/guides/setup-cdk/module-three/ and I'm running into the same issue. In my case the it seems the tutorial is written for the V1 libraries, while V2 is now the default install. So following the tutorial results in trying to use V1 and V2 libraries at the same time. I was able to fix it with some knowledge of JavaScript and some googling, and I figured how to use V2, but it's less than ideal. I think the tutorial documents need updating to use V2 so that new people don't have to get so confused.

So, How did you resolve it? I have no Javascrip knowledge and i am stuck on same error for the past hour

commented

I'm just going through the AWS getting started tutorials: https://aws.amazon.com/getting-started/guides/setup-cdk/module-three/ and I'm running into the same issue. In my case the it seems the tutorial is written for the V1 libraries, while V2 is now the default install. So following the tutorial results in trying to use V1 and V2 libraries at the same time. I was able to fix it with some knowledge of JavaScript and some googling, and I figured how to use V2, but it's less than ideal. I think the tutorial documents need updating to use V2 so that new people don't have to get so confused.

So, How did you resolve it? I have no Javascrip knowledge and i am stuck on same error for the past hour

Yeah good point! I'm not used to being the one to post the answer haha!
I decided to only use the V2 library, which keeps all the old V1 stuff at bay. So I blew away all of the V1 stuff from my stack definition file as well as the package.json files. But I had to find where the function calls were buried in the library so I could include them appropriately...
The documentation page for the Vpc constructor is here
As you can see, the Vpc function is can be found at: aws-cdk-lib » aws_ec2 » Vpc
So I decided to include all of aws_ec2 with this line:
import { aws_ec2 as ec2 } from 'aws-cdk-lib;
Then I called the Vpc function like this:
const vpc = ec2.Vpc.fromLookup(this, "VPC", { isDefault: true });
I followed this process for all of the other functions I needed: Find the documentation page, figure out where the function lives in the aws-cdk-lib, and include that location with an appropriate name.
I hope this helps!

I'm just going through the AWS getting started tutorials: https://aws.amazon.com/getting-started/guides/setup-cdk/module-three/ and I'm running into the same issue. In my case the it seems the tutorial is written for the V1 libraries, while V2 is now the default install. So following the tutorial results in trying to use V1 and V2 libraries at the same time. I was able to fix it with some knowledge of JavaScript and some googling, and I figured how to use V2, but it's less than ideal. I think the tutorial documents need updating to use V2 so that new people don't have to get so confused.

So, How did you resolve it? I have no Javascrip knowledge and i am stuck on same error for the past hour

Yeah good point! I'm not used to being the one to post the answer haha! I decided to only use the V2 library, which keeps all the old V1 stuff at bay. So I blew away all of the V1 stuff from my stack definition file as well as the package.json files. But I had to find where the function calls were buried in the library so I could include them appropriately... The documentation page for the Vpc constructor is here As you can see, the Vpc function is can be found at: aws-cdk-lib » aws_ec2 » Vpc So I decided to include all of aws_ec2 with this line: import { aws_ec2 as ec2 } from 'aws-cdk-lib; Then I called the Vpc function like this: const vpc = ec2.Vpc.fromLookup(this, "VPC", { isDefault: true }); I followed this process for all of the other functions I needed: Find the documentation page, figure out where the function lives in the aws-cdk-lib, and include that location with an appropriate name. I hope this helps!

Thanks Nathan, i will try this out and give you feedback!

If you're doing a tutorial, just blow away the contents of hello-cdk directory or (w/e it is) and then run the "cdk init app --language typescript" again (in the recreated directory). After you make sure all your CDK stuff is latest with: "npm list" and then "npm view aws-cdk versions" and repeat for "aws-cdk-lib"