Error in Typescript: A computed property name must be one of the types 'string', 'number', 'symbol', or 'any'

Here is the current code I am working with:

interface sizes {
  [key: string]: Partial<CSSStyleDeclaration>[];
}

export const useStyleBlocks = (
  resolution = 'large',
  blocks = [{}]
): Partial<CSSStyleDeclaration>[] => {
  const starterBlock = [] as Partial<CSSStyleDeclaration>[];
  const handleBlocks = (key: sizes): Partial<CSSStyleDeclaration>[] => {
    for (let i = 0; i < blocks.length; i++) {
      // The error occurs on this line specifically at [key]
      // A computed property name must be of type 'string', 'number', 'symbol', or 'any'
      starterBlock.push({ [key]: blocks });
    }

    return starterBlock;
  };

  switch (resolution) {
    case 'small':
      // Another error appears here
      // Argument of type 'string' is not assignable to parameter of type 'sizes'
      handleBlocks('small');
      break;
    default:
      handleBlocks({});
      break;
  }

  return starterBlock;
};

The explanation of errors can be found commented within the code above ^

Any suggestions or ideas?

UPDATE:

If I modify the function handleBlocks like so:

  const handleBlocks = (key: string): Partial<CSSStyleDeclaration>[] => {
    for (let i = 0; i < blocks.length; i++) {
/* NOW I ENCOUNTER A NEW ERROR:
Argument of type '{ [x: string]: {}[]; }' is not assignable to parameter of type 'Partial<CSSStyleDeclaration>'.
Index signatures are incompatible.
Type '{}[]' is not assignable to type 'string'.ts(2345) */
      starterBlock.push({ [key]: blocks });
    }

    return starterBlock;
  };

With that adjustment, the error in the switch statement no longer persists.

Answer №1

Here's the breakdown:

const handleBlocks = (key: sizes): Partial<CSSStyleDeclaration>[] => {

The essence of this code snippet is that handleBlocks expects an argument of type sizes, which is essentially an object. But when you actually invoke handleBlocks, you're providing a string ('small').

As a result, it throws an error since you're trying to use an object type as a computed property name, given that key is of type sizes, which signifies an object.

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

TS2345: Cannot assign type '(item: cType) => cType' to type '(value: Object, index: number, array: Object[]) => cType' within the parameter

I am currently working on a project using Angular 13 and Typescript 4.5.2. In addition, I am incorporating the Syncfusion library in my development process, specifically utilizing the datagrid component for managing table data. For reference, you can che ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...

Connecting an Angular 4 Module to an Angular 4 application seems to be causing some issues. The error message "Unexpected value 'TestModule' imported by the module 'AppModule'. Please add a @NgModule annotation" is

Update at the bottom: I am currently facing a massive challenge in converting my extensive Angular 1.6 app to Angular 4.0. The process has turned into quite a formidable task, and I seem to be stuck at a specific point. We have a shared set of utilities th ...

Periodically transmit information to a Google Script web application

I am currently working on a Google Script web app to automatically update data from a Google Sheet every 30 minutes. I initially attempted using the page refresh method, but encountered an issue where the web app would display a blank page upon refreshin ...

Encountering the error message "Error: 'preserveValueImports' is an unknown compiler option" while setting up a SvelteKit project

https://i.stack.imgur.com/fnidk.png Every time I set up a new sveltekit project using TypeScript, I keep encountering the error "Unknown compiler option 'preserveValueImports'.ts" in the tsconfig.json file. The error shows up above the line wher ...

Unable to populate data in dropdown using Angular framework?

My datatable displays elements along with an edit button. At the top of the page, there is also an add button. The purpose of the add button is to add elements to the list, while the edit button allows for editing the data in a particular row. When the u ...

The JSON file overwrites entire objects instead of targeting individual ones

Is there a way to update just one specific object in a JSON file without affecting the rest? I've implemented a put request on the front-end using axios to send data to the back-end for processing. However, the current functionality replaces all obje ...

Tips for implementing X-XSS-Protection: 1; mode=block in HTML

I'm struggling with where to place this piece of code in my existing code. Should it be added to the header section? <head> <meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" /> <title> ...

Invoke a function from a different source in JavaScript

Below is the JS function implemented: function addMemberToLessonDirect(id) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } ...

Unit testing the TypeScript function with Karma, which takes NgForm as a parameter

As I work on writing unit tests for a specific method, I encounter the following code: public addCred:boolean=true; public credName:any; public addMachineCredential(credentialForm: NgForm) { this.addCred = true; this.credName = credentialForm.val ...

What is the process for using the CLI to downgrade an NPM package to a previous minor version by utilizing the tilde version tag?

I currently have Typescript version ^3.7.4 installed as a devDependency in my project's package.json: { "name": "my-awesome-package", "version": "1.0.0", "devDependencies": { "typescript": "^3.7.4" } } My goal is to downgrade Typescript ...

React's JS is having trouble accepting cookies from the express server

I've encountered an issue where sending cookies from my express server using res.cookie() is not working with the front end. Even though I include {withCredentials:true} in the get requests, the cookies are not being set in the browser's applicat ...

Add a Page to Your Domain Name using the Text Input Box

I'm looking to create an input field that allows users to enter a text string, which will be added to a domain name when submitted, redirecting the user to a specific page. Here's how the process works: The user enters 'foo' into the ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

Guide on importing an external JavaScript library in Node.js utilizing a TypeScript declaration file

I am working on a Node.js project using Typescript and I am facing an issue with integrating mime.js (https://github.com/broofa/node-mime). Even though I have a declaration file available (https://github.com/borisyankov/DefinitelyTyped/blob/master/mime/mim ...

Using discord.js within an HTML environment can add a whole new level of

I'm in the process of creating a dashboard for discord.js, however, I am facing difficulties using the discord.js library and connecting it to the client. Below is my JavaScript code (The project utilizes node.js with express for sending an HTML file ...

Implementing authentication middleware with React Router in a React component

Working on my app.js, I'm trying to implement an Auth component that acts as middleware to check if the user is logged in. const App = props => ( <BrowserRouter> <Provider store={store}> <div className="app"& ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

Losing focus issue with Material-UI TextField occurs constantly with every onChange event

I am in the process of developing a new component: https://i.stack.imgur.com/czM9i.png This component will consist of an array of objects, each representing a prescription. Each object will include the medicine name selected from a dropdown and a text fi ...