The parameter of type "Construct" cannot be assigned the argument of type "undefined"

I attempted to use code example from the AWS CDK documentation, but it did not function as I had anticipated.

Using CDK version 2.62.2 with Typescript. In various parts of the code, a declaration error occurs stating that

The argument of type "undefined" cannot be assigned to the parameter of type "Construct"
.

Code:

import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';

declare const vpc: ec2.Vpc;

// Creating an ECS cluster
const cluster = new ecs.Cluster(this, 'Cluster', { vpc });

// Adding capacity to the cluster
cluster.addCapacity('DefaultAutoScalingGroupCapacity', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
  desiredCapacity: 3,
});

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');

taskDefinition.addContainer('DefaultContainer', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 512,
});

// Initializing an Amazon ECS Service
const ecsService = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
});

Answer №1

TL;DR The issue arises from the fact that the this keyword is undefined in your code. To resolve this, you should move your instantiation code to a construct subclass constructor.


When defining a construct in CDK, the first argument is its scope, or parent construct. While using the this keyword as the scope is correct, it is currently undefined in your code. The recommended CDK approach is to define constructs inside the constructor of a construct subclass, typically a Stack. Within the Stack's constructor, the reference to this will point to the Stack instance.

Additionally, in your code, the variable vpc is also undefined. It's worth noting that the CDK documentation often uses TypeScript variable declaration statements for brevity. Although this may not be causing an error, it might not yield the expected behavior. To avoid default Vpc creation (if vpc prop is undefined), make sure to instantiate a Vpc rather than simply declaring the vpc variable.

class MyStack extends Stack {
  constructor(scope: App, id: string, props?: StackProps) {
    super(scope, id, props);

    const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 2 });

    const cluster = new ecs.Cluster(this, 'Cluster', { vpc });
  }
}

For complete working ECS examples for EC2, you can explore the aws-samples/aws-cdk-examples repository.

Answer №2

When creating a new ecs.Cluster, it's important to ensure that you define a valid VPC instead of passing along an "Undefined" value. Simply declaring the constant without assigning a value can lead to errors.

To properly create a new VPC, consider updating the line from:

declare const vpc: ec2.Vpc;

To something like:

const vpc = new ec2.Vpc(this, 'TheVPC')

For more information on this topic, refer to the documentation available at https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Building a TypeScript Rest API with efficient routing, controllers, and classes for seamless management

I have been working on transitioning a Node project to TypeScript using Express and CoreModel. In my original setup, the structure looked like this: to manage users accountRouter <- accountController <- User (Class) <- CoreModel (parent Class o ...

Unable to locate module within Typescript

Hello everyone, I am facing a problem similar to this one: I have an app written in TypeScript, and within it, I have imported import { Component } from '@angular/core'; import {CORE_DIRECTIVES} from '@angular/common'; import { MODA ...

Discover the magic of observing prop changes in Vue Composition API / Vue 3!

Exploring the Vue Composition API RFC Reference site, it's easy to find various uses of the watch module, but there is a lack of examples on how to watch component props. This crucial information is not highlighted on the main page of Vue Composition ...

The object may be null even after being enclosed in an if statement

In my Vue component, I have implemented the following method: dataURLtoBlob(dataurl: string): Blob { const arr: string[] = dataurl.split(","); if (arr) { if (arr[0]) { const mime = arr[0].match(/:(.*?);/)[1]; ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Setting up grunt-ts to function seamlessly with LiveReload

I am currently experimenting with using TypeScript within a Yeoman and Grunt setup. I've been utilizing a Grunt plugin called grunt-ts to compile my TypeScript files, and while the compilation process is smooth, I'm encountering issues with live ...

Combining Different Types of Errors

Can TypeScript's type system be exploited to provide additional information from a repository to a service in case of errors? I have a service that needs a port for a repository (Interface that the Repository must implement), but since the service mu ...

Infer the types and flatten arrays within arrays

I am currently working on creating a custom function in typescript that can flatten nested arrays efficiently. My current implementation is as follows: function flattenArrayByKey<T, TProp extends keyof T>(array: T[], prop: TProp): T[TProp] { re ...

Unable to import necessary modules within my React TypeScript project

I am currently building a React/Express application with TypeScript. While I'm not very familiar with it, I've decided to use it to expand my knowledge. However, I've encountered an issue when trying to import one component into another comp ...

Extending the Object prototype within an ES6 module can lead to errors such as "Property not found on type 'Object'."

There are two modules in my project - mod1.ts and mod2.ts. //mod1.ts import {Test} from "./mod2"; //LINE X interface Object { GetFooAsString(): string; } Object.prototype.GetFooAsString = function () { return this.GetFoo().toString(); } //mod2. ...

Issue with Angular 2 Observable not triggering the complete function

I've been experimenting with the hero app tutorial for Angular 2 and currently have this Component set up: import { Component, OnInit } from '@angular/core' import { Subject } from 'rxjs/Subject'; import { Hero } from "./hero"; im ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

Combine values from 2 distinct arrays nested within an array of objects and present them as a unified array

In my current array, the structure looks like this: const books[{ name: 'book1', id: '1', fromStatus: [{ name: 'Available', id: 1 }, { name: 'Free', id: 2 }], t ...

Storing API URLs in a configuration file for a React application hosted on AWS S3: Best Practices

WHAT IS THE ISSUE? I currently have a React application deployed on AWS S3 that retrieves data from an API URL and displays the response. The challenge lies in the fact that the API URL varies depending on the environment. In the development (DEV) enviro ...

Exploring the integration of an Angular 4 application with Visual Studio 2017 using dot net core. Techniques for accessing configuration keys from appsetting.json in a TypeScript

I'm currently working on an Angular 4 application using Visual Studio 2017 with .NET Core. I need to figure out how to access configuration keys from appsetting.json in my TypeScript file. I know how to do it in the startup.cs file, but I'm strug ...

<Click here to navigate to page 2> await whenClicked={navigation.navigate("page_2")} />

Issue with assigning a 'string' to a parameter in TypeScript while trying to navigate to another screen in React Native. Can anyone help with this error? This problem occurs when we want to navigate to another screen using TypeScript in React Na ...

Assigning a dynamic name to an object in Typescript is a powerful feature

Is there a way to dynamically name my object? I want the "cid" value inside Obj1 to be updated whenever a new value is assigned. I defined it outside Obj1 and then called it inside, but when I hover over "var cid," it says it's declared but never used ...

Using memoization for React Typescript callback passed as a prop

My component is designed to display data retrieved from a callback provided in the props. To prevent an infinite loop caused by mistakenly passing anonymous functions, I am looking for a method to enforce the usage of memoized callbacks. const DataRenderer ...

The 'type' property is not present in the 'ChartComponent' type, however, it is necessary in the 'ApexChart' type

Encountered an error highlighted in the title: Property 'type' is missing in type 'ChartComponent' but required in type 'ApexChart'. Any attempt to resolve this issue led to another error message: Type '{ type: string; ...