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

What is the method for achieving the equivalent effect of "background-size: cover" on an <img>?

I am looking to ensure that an <img> has the smallest possible size without any empty spaces inside a div, while also being perfectly centered both horizontally and vertically. The image size may vary. To better illustrate, here is an example: http: ...

Counting nodes that have the 'enabled' property: A guide

I am dealing with a tree structure that has Node objects: class Node implements ITreeNode { id?: any; name: string; children:? Node[], enabledState = new Subject<boolean>(); toggle() { this.enabled = !this.enabled; this.enabledStat ...

An error occurs when using e.slice function

I am facing an issue with my kendoDropDownList that uses kendo UI and jQuery. I cannot figure out why this error is occurring. $("#drpState").kendoDropDownList({ optionLabel: "States...", delay: 10, ...

VIDEOJS ERROR: A peculiar mistake has occurred. TypeError: The property 'value' cannot be read since it is undefined in the context of

Recently, I came across a fascinating plugin called videojs-thumbnails for video.js, and I'm eager to incorporate it into my angular component. However, I keep encountering an error that says: VIDEOJS: ERROR: TypeError: Cannot read property 'val ...

Simulate a click event on an element generated with JavaScript to initiate the download of a CSV file

I am attempting to generate an HTML element and trigger a click event in order to download a CSV file upon receiving an ajax response (the data array provided is for testing purposes only). $(document).on('click','.csv',function(){ ...

Can we use a switch statement instead of having multiple @Input()s in Angular?

When passing an attribute into my Angular component like this: <my-component myAttribute></my-component> I aim to modify a variable within the component that controls the CSS properties for width and height. To simplify, I have predefined at ...

Issue encountered: Nuxt 3 fails to locate the useRoute import

Recently, I updated to the latest version of Nuxt and encountered an issue with the useRoute method. Even though it works, I keep getting a "Cannot Find name useRoute" error message. Can anyone help me figure out what might be missing? <script lang=&quo ...

Manipulating State in React: How to add a property to an object within an array within a component's state

Currently, I am retrieving an array of objects stored in the state, and I am attempting to include a new property to each of these objects. However, I am encountering a problem where even though I can see the new property being added to each object, when ...

How can we create responsive websites?

Since starting my Software Developer studies about 3 months ago, I've been working on a website project for a driving school with a team of four. The issue we're facing is that when we transfer and open files between laptops, the website layout a ...

Why is my Javascript XMLHttpRequest onreadystatechanged event not triggering?

I am facing an issue with my html file and a .txt file stored in the same directory on a webserver. In the html file, I have the following code: <html> <head> <script> window.onload = function() { receiveMessage(); } function recei ...

Retrieve a file from a remote server without storing it locally on the server

I need to download a zip file from another server without saving it locally. Currently, I am sending a POST request to the server which responds with the zip file, then I save it on my local server and send it using res.download. What I would like is to di ...

Disable hover effects in CSS with JavaScript

I am looking for a way to deactivate CSS hover functionality using JavaScript. Within a form, there is a button that sends data to the database server. By utilizing OnClientClick() of an ASP.NET Button control, my goal is to modify the text of the element ...

Angular issue: Readonly or disabled input fields not submitting data

Struggling with creating a form in Angular 2 to submit dynamically generated values from a service. The goal is to calculate the equivalent amount of bitcoin for X chilean pesos using Angular's http module to fetch the price. However, facing an issue ...

Display an Asterisk Icon for md-input fields with lengthy labels

Documentation states that md-inputs add an asterisk to the label if it is a required type. However, when input containers have width constraints and long labels, the label gets truncated and the asterisk becomes invisible. From a user experience perspectiv ...

What could be the reason behind receiving a TypeError upon refreshing the page, where it claims that a state is not found even though that may not be the actual situation?

Within my application, I have a component called Wall. Users are redirected to the Wall component after successfully logging in from the Login component. In the Wall component, I am retrieving and displaying the user's name that they used during regis ...

What are some ways to customize the appearance of React Semantic components?

Is there a way to apply CSS for react semantic UI when using create react app? I have installed semantic-ui-react and included the CSS CDN: loginForm.js: import React from "react"; import { Button, Form, Header } from "semantic-ui-react"; import styles f ...

Guide on verifying the presence of an alert with nodejs webdriver (wd)

I am currently facing a challenge when writing a test where I need to verify the existence of an alert, check its text if it is present, and then accept it. Although I have researched on platforms like Stack Overflow for solutions such as checking for ale ...

No value found for Req.file using the express-fileupload and multer libraries

I have exhausted all possible scenarios and attempted various variations and methods recommended in the documentation and from other sources like Stack Overflow. However, none of them seem to work -> I constantly receive req.file is: undefined Here is ...

(React Native) Creating a visually appealing grid layout for displaying an array of item cards

I am working with two arrays named 'word' and 'definition' export default class Dictionary extends React.Component { constructor(props) { super(props); this.state = { word: [], definition:[], index: ...

Customize your Loopback 4 OpenAPI with NSWAG by making filters optional and specifying data types

I am encountering an issue with the Loopback 4 filter on the generated endpoints being marked as required in my Nswag typescript file. I need it to be optional, but I am struggling to locate where this requirement is originating from. The endpoint from my ...