Non
Non

Reputation: 8589

Typescript error: A computed property name must be of type 'string', 'number', 'symbol', or 'any'

This is my current code:

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 comes from this line exactly on [key]
      // A computed property name must be of type 'string', 'number', 'symbol', or 'any'
      starterBlock.push({ [key]: blocks });
    }

    return starterBlock;
  };

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

  return starterBlock;
};

The explanation about the errors are commented within the code above ^

Any ideas?

UPDATE:

If I change the function handleBlocks to:

  const handleBlocks = (key: string): Partial<CSSStyleDeclaration>[] => {
    for (let i = 0; i < blocks.length; i++) {
/* HERE I GET 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 change, the error on the switch statement is gone.

Upvotes: 0

Views: 3761

Answers (1)

MikeTheReader
MikeTheReader

Reputation: 4190

This line:

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

is saying that handleBlocks wants an argument of type sizes, an interface that is an object, but when you call handleBlocks, you're passing in a string ('small').

Then, it's complaining that you're trying to use an object type for a computed property name, since key is of type sizes, which is an object.

Upvotes: 4

Related Questions