Utilizing AWS CDK to Define StackProps Input Variables

Recently, I have started using the AWS CDK and encountered a challenge. I want to allow end users to define custom input variables when using my AWS CDK without having to edit the entire code. While I have been able to work with standard types such as strings, numbers, and booleans, I am unsure of how to handle custom types. For instance, when attempting to create an AWS DynamoDB, I first defined an interface to ensure that users can input the required data accurately.

Below is the interface I created:

export interface IDynamoDB extends StackProps {
    tableClass:       unknow,
    billingMode:      unknown
    sortKeyName:      string,
    sortKeyType:      unknown,
    partitionKeyName: string,
    partitionKeyType: unknown
    inTimeRecovery:   boolean
}

Here is the corresponding class:

export class Ddb extends Stack {
    constructor(scope: Construct, name: string, props: IDynamoDB) {
        super(scope, name, props);


        const table = new ddb.Table(this, name, {
            tableName:      name,
            tableClass:     ddb.TableClass.STANDARD,
            billingMode:    ddb.BillingMode.PROVISIONED,
            sortKey: {
                    name: props.sortKeyName,
                    type: ddb.AttributeType.NUMBER
            },
            partitionKey: {
                    name: props.partitionKeyName,
                    type: ddb.AttributeType.STRING
            },
        })
    }
}

Imports

import { Construct } from 'constructs';
import { Stack, StackProps } from 'aws-cdk-lib';
import * as ddb from 'aws-cdk-lib/aws-dynamodb';

My issue lies with the interface where I used unknown as a type, and I am unsure how to simplify it further. Ideally, I would like to be able to just use a string as shown below:

ddb.TableClass.STANDARD = standartTableClass

I hope this explanation clarifies my problem.

Answer №1

Typically, the props within your code would have the same ddb Enum types as the construct (refer to tableClass below). However, in order to optimize for shorter values as mentioned in your comment, it is possible to define your props using the string values of the Enum and then look up the type in your constructor (see billingMode).

export interface IDynamoDB extends StackProps {
  tableClass: ddb.TableClass;
  billingMode: "PROVISIONED" | "PAY_PER_REQUEST"; // string values of the Typescript Enum type
  sortKeyName: string;
  sortKeyType: ddb.AttributeType;
  partitionKeyName: string;
  partitionKeyType: ddb.AttributeType;
  inTimeRecovery: boolean;
}

table constructor:

tableClass:     props.tableClass,
billingMode:    ddb.BillingMode[props.billingMode], // map the enum

Some points to consider regarding the billingMode approach: (1) you may want to implement stricter validations and (2) your users might lose intellisense documentation context.

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

There seems to be an issue with Material-UI and TypeScript where a parameter of type 'string' does not have an index signature in the type 'ClassNameMap<"container" | "navBar" | "section0">'

My current project is encountering a TS Error stating "(No index signature with a parameter of type 'string' was found on type 'ClassNameMap<"container" | "navBar" | "section0">'.)" The code below is used to assign styles to vari ...

What is the best way to have Vue i18n fetch translations from a .json file during Unit Testing?

Previously, with vue-i18n (v8.25.0 and vue v2.6.14), I stored all translations in .ts files containing JS objects: import { LocaleMessages } from 'vue-i18n' const translations: LocaleMessages = { en: { test: 'Test', }, } expor ...

TypeScript equivalent to Python's method for removing non-whitespace characters is achieved by

I understand that I can utilize .trim() to eliminate trailing spaces Is there a method to trim non-space characters instead? In [1]: str = 'abc/def/ghi/' In [2]: s.strip('/') Out[2]: 'abc/def/ghi' I am referring to the funct ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

Retrieving the value of an object using an array of keys

Consider the following object: const obj = { A:{ a1:'vala1', a2:'vala2' }, B:{ b1: 'valb1', b2: 'valb2' }, C:{ c1:{ c11:'valc11' }, c2:'valc2' } } We also have an array: const ...

Question about TypeScript annotations: arrays containing key-value pairs

Is there an explanation for why this issue occurs in VSCode? interface Point { x: number; y: number; } let grid: [key: number, value: [key: number, value: Point]]; // ... // Accessing an object of type number | [key: number, value: Point] var c ...

Create a debounced and chunked asynchronous queue system that utilizes streams

As someone who is new to the concept of reactive programming, I find myself wondering if there exists a more elegant approach for creating a debounced chunked async queue. But what exactly is a debounced chunked async queue? While the name might need some ...

Guide on placing a numerical value within the source_mappings.json file in an AWS SDLF pipeline

Utilizing a framework known as the Serverless DataLake Framework (SDLF), files can be ingested into an AWS S3 DataLake. Certain configurations are required to move a file through various stages within the S3 repository. The initial step involves transferri ...

Querying data elements using Graphql mutations: a step-by-step guide

const MUTATION_QUERY = gql` mutation MUTATION_QUERY( $name: bigint! ) { insert_name( objects: { name: $name } ) { returning { id name } } } `; const [onClick, { error, data }] = useMut ...

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

Types of Axios responses vary depending on their status codes

I am looking to create a specific type for axios responses based on the status code: types: type SuccessfulResponseData = { users: .... }; interface SuccessfulResponse extends AxiosResponse<SuccessfulResponseData, any> { status: 200; } ty ...

Is there a way to customize the Color Palette in Material UI using Typescript?

As a newcomer to react and typescript, I am exploring ways to expand the color palette within a global theme. Within my themeContainer.tsx file, import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@mate ...

BehaviorSubject Observable continuously notifies unsubscribed Subscription

Utilizing a service called "settings", initial persisted values are read and provided through an observable named "settings$" to components that subscribe to it. Many components rely on this observable to retrieve the initial values and exchange updated va ...

Ways to add a React Router Link to a Material UI TableRow

When attempting to incorporate a Link component from React Router Dom into my Material UI TableRow, I encountered an issue. <TableRow component={Link as any} to={`/company/${company.id}`} className="clt-row" key={company.id}> The error message I re ...

No response was forthcoming

I have been trying to send a post request to my login endpoint, but I am not receiving any response. Despite thoroughly checking my code, I am unable to figure out why there is no response being sent back. My backend is built using Express in TypeScript. B ...

Order of Execution

I am facing an issue with the order of execution while trying to retrieve values from my WebApi for input validation. It appears that the asynchronous nature of the get operation is causing this discrepancy in execution order. I believe the asynchronous b ...

Customize back button functionality in Ionic 2

Is it possible to modify the behavior of the back button shown in this image? I would like to specify a custom destination or perform an action before navigating back, instead of simply returning to the previous page. https://i.stack.imgur.com/EI2Xi.png ...

Is there a suitable alternative that supports TypeScript, particularly with Angular 6, as D3Js does not directly support TypeScript?

I am currently engaged in a new project focusing on HR Analytics, utilizing Python, R, MySQL, and Angular 6 for the front end user interface. In terms of Data Visualization, I am exploring the use of D3js. However, it is important to note that D3Js does no ...

Utilize Docker on AWS for seamless deployment and execution

After completing my React and NodeJS projects, I created a Dockerfile for each one and then a docker-compose file to generate docker images for both the frontend and backend. I have also uploaded the images to my repository on Docker hub. Now, I want to r ...