簡體   English   中英

元素隱式具有“任何”類型,因為索引表達式不是“數字”類型[7015]

[英]Element implicitly has an 'any' type because index expression is not of type 'number' [7015]

我從David Walsh的css動畫回調中獲取了代碼並將其修改為TypeScript。 但是,我收到一個錯誤,我不知道為什么:

interface IBrowserPrefix {
  [key: string]: string;
}

// http://davidwalsh.name/css-animation-callback
function whichAnimationEvent() {
  let x: keyof IBrowserPrefix;
  const el = document.createElement('temp');
  const browserPrefix: IBrowserPrefix = {
    animation: 'animationend',
    OAnimation: 'oAnimationEnd',
    MozAnimation: 'animationend',
    WebkitAnimation: 'webkitAnimationEnd',
  };

  for (x in browserPrefix) {
    if (el.style[x] !== undefined) {
    //           ^---- [TS Error]: Element has 'any' type b/c index expression is not of type 'number'
      return browserPrefix[x];
    }
  }
}

發生這種情況是因為您嘗試使用帶有字符串鍵的數字索引簽名來索引對象。

for x in browserPrefix將為您提供一組鍵,這些鍵是字符串。 但是由於某些原因, CSSStyleDeclaration的索引類型設置為number (而不是string ) - 請參閱https://github.com/Microsoft/TypeScript/issues/17827

您收到此錯誤是因為您已--noImplicitAny 讓這個工作(一種hacky方式)的方法是將索引器轉換為字符串:

  for (x in browserPrefix) {
    if (el.style[x as any] !== undefined) {
      return browserPrefix[x];
    }
  }

另一種方法是修改類型(嘗試在github上碰撞問題)。

當我們在這里時,你應該用const標記x ,如果你要在對象上使用for-in,你應該確保該屬性屬於該對象,以避免拉入原型鏈中繼承的任何內容:

  for (const x in browserPrefix) {
    if (browserPrefix.hasOwnProperty(x) && el.style[x as any] !== undefined) {
      return browserPrefix[x];
    }
  }

或者,使用for-ofObject.keys ,而不是for-in

這里沒有必要提前定義x

嘗試for (x of Object.keys(browserPrefix))而不是for (x in browserPrefix)

通常不贊成使用in關鍵字作為循環,因為您可能獲得不屬於該對象的屬性

代碼中存在幾個問題,第一個問題是IBrowserPrefix被定義為具有字符串索引,因此具有keyof IBrowserPrefix; 實際上是字符串。 我會刪除界面,只需使用let x: keyof typeof browserPrefix;

下一個問題是typescript定義CSSStyleDeclaration接口的方式。 它只包括標准屬性,而不是特定於供應商的屬性。

您可以使用類型斷言告訴編譯器您知道自己在做什么並忽略錯誤

export function whichAnimationEvent() {

    const el = document.createElement('temp');
    const browserPrefix = {
        animation: 'animationend',
        OAnimation: 'oAnimationEnd',
        MozAnimation: 'animationend',
        WebkitAnimation: 'webkitAnimationEnd',
    };
    let x: keyof typeof browserPrefix;
    for (x in browserPrefix) {
        if (el.style[x as keyof CSSStyleDeclaration] !== undefined) {
            return browserPrefix[x];
        }
    }
}

您還可以使用CSSStyleDeclaration擴展您需要的供應商特定密鑰。

暫無
暫無

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

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