How to resolve TypeScript error TS2322 when a function returns an interface


export interface AWSTags {
  CreatedBy: string;
  Environment: EnvironmentMap;
  Name: string;
  OwnedBy: string;
  Platform: string;
  Product: string;
  Runbook: string;
  Service: string;
}

Another script contains the following function to generate an object that adheres to the specified interface.

export const getAWSTags = (stackName: string, environment: EnvironmentMap, createdBy: string): AWSTags => ({
  CreatedBy: createdBy,
  Environment: environment,
  Name: stackName,
  OwnedBy: "owner",
  Platform: "platform",
  Product: "product",
  Runbook: "url",
  Service: `${stackName}-service`,
});

Just for clarity, EnvironmentMap is a data type that can return one of three strings.

When attempting to assign the result of this function to AWS tags, which requires the structure shown below, error code 2322 is encountered.

readonly tags?: {
  [key: string]: string;
};
const app = new App();
const stack = new Stack(app, stackName, {
  env: {
    account: AWS.ACCOUNT,
    region: AWS.REGION,
  },
  tags: getAWSTags(stackName, environment, 'creator'),
});
Type 'AWSTags' is not assignable to type '{ [key: string]: string; }'. Index signature for type 'string' is missing in type 'AWSTags'.ts(2322)

Are there different methods or alternatives available to resolve this issue?

UPDATE: The error seems to be resolved by modifying the interface as follows.

export interface AWSTags {
  [key: string]: string;
  CreatedBy: string;
  Environment: EnvironmentMap;
  Name: string;
  OwnedBy: string;
  Platform: string;
  Product: string;
  Runbook: string;
  Service: string;
}

Thank you

Answer №1

The issue lies in the fact that, even though the final JS code remains unchanged, you are passing an object instance into a function that is expecting a Plain Old JavaScript Object.

Essentially, what this TypeScript interface does is define a template for an object with specific properties, but that doesn't restrict your object from having additional values.

To resolve this issue, it's recommended to switch from using an interface to just defining a simple type:

export type AWSTags = {
  CreatedBy: string;
  Environment: EnvironmentMap;
  Name: string;
  OwnedBy: string;
  Platform: string;
  Product: string;
  Runbook: string;
  Service: string;
}

Alternatively, if you prefer to stick with interfaces, you can destructure the resulting object before passing it into tags:

const stack = new Stack(app, stackName, {
  // ...
  tags: {...getAWSTags(stackName, environment, 'creator')},
});

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

Is it true that Angular 4 routers only maintain a single state during navigation?

After transitioning from state A to state B in my application, I noticed that when navigating back to state A, it seems to reload. Does this mean that State A is being destroyed during the transition to state B? If so, how can I prevent State A from relo ...

Encountering path import errors when developing a sample webpack site within a TypeScript library

Struggling to integrate my custom library with TypeScript and Webpack. Import errors are causing headaches, despite smooth sailing in CLion. Running tsc within the project directory is error-free, unlike when running npm run dev in the examples/webpack di ...

Display corresponding JSON images of items within an *ngFor loop in Angular

For my latest project, I am using Angular for the front-end and Laravel for the back-end. The issue I'm facing is with displaying images in Angular that are stored in Laravel storage. The image URLs are stored in the database in JSON format like this: ...

Error during Webpack Compilation: Module 'jQuery' not found in Travis CI with Mocha Test

I've been struggling to automate tests for my repository using mocha-webpack and Travis CI. The local machine runs the tests smoothly, but Travis CI hasn't been able to complete them yet due to an unresolved error: WEBPACK Failed to compile wit ...

What causes typescript to trigger compilation errors in react-scripts when using certain keywords?

Struggling with a bizarre issue involving TypeScript and React Scripts Line 5:16: Parsing error: Unexpected token 3 | class AutoUpdateBase<TBinding> implements IAutoUpdate<TBinding>{ 4 | > 5 | protected binding?: (arg: TBinding) ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Splitting a string in Typescript based on regex group that identifies digits from the end

Looking to separate a string in a specific format - text = "a bunch of words 22 minutes ago some additional text". Only interested in the portion before the digits, like "a bunch of words". The string may contain 'minute', & ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

Unable to assign the value 'hello' to an undefined property in TypeScript

I'm attempting to define a class in TypeScript, but I keep encountering the error shown below. Here is the execution log where the error occurs: [LOG]: "adding" [LOG]: undefined [ERR]: Cannot set property 'hello' of undefined class Cust ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Angular: Updating image tag to display asynchronous data

Utilizing Angular to retrieve user profile pictures from the backend, specifically Node.js/Express, has been mostly successful. However, there is one issue that I have encountered. The HTML displaying the profile picture does not re-render when the user up ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...

What is the best approach for managing and obtaining accurate JSON responses when working with PHP API and AngularJS 2 services?

Encountering a backend issue with MySQL, wherein one query is producing a specific dataset: {"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz"," ...

"Alert in Javascript executing prematurely prior to initiating the function for sending a get request

private validateURL(url: string) { let isValid = false; this.$http.get(url).then( (data) => { console.log('success'); isValid = true; } ).catch( (reason) => { console. ...

Function that observes with the pipe syntax

Is it possible to apply map, switchMap, or any other operator in conjunction with a function that outputs an observable? The objective here is to transform the result of the observable function and utilize that value during the subscription to another ob ...

What is the best way to implement persistStore in Redux-Toolkit?

Here is my setup: import AsyncStorage from '@react-native-async-storage/async-storage' import { persistStore, persistReducer } from 'redux-persist'; import { configureStore } from "@reduxjs/toolkit"; import { searchReducer } f ...

Setting up Mailgun with TypeScript on Firebase Cloud Functions

Currently, I am working on a Cloud Function within Firebase to integrate with Mailgun for sending emails, following the guidelines provided in the Mailgun documentation. My challenge lies in implementing this functionality using TypeScript, as I have been ...

Properties for a standard React component

Currently, I am developing a form component in react with typescript that requires a 'fieldStructures' and an 'onSubmit' prop. type FieldStructure { type: 'text'; name: string; label?: string; helpText?: string ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...