簡體   English   中英

打字稿錯誤:計算的屬性名稱必須是“字符串”、“數字”、“符號”或“任何”類型

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

這是我當前的代碼:

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;
};

關於錯誤的解釋在上面的代碼中進行了注釋^

有任何想法嗎?

更新

如果我將函數handleBlocks更改為:

  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;
  };

有了這個改變, switch語句上的錯誤就消失了。

這一行:

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

是說, handleBlocks想要類型的參數sizes ,這是一個對象的接口,但是當你調用handleBlocks ,你傳遞一個字符串(“小”)。

然后,它抱怨您試圖將對象類型用於計算屬性名稱,因為key的類型是sizes ,它是一個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM