0

I have a problem with determining what is the correct index-signature when enabling "noImplicitAny" in the typescript.

const getFromUri = () => {
  const urlSearch = window.location.search.substring(1);
  const params: { foo?: number; bar?: number } = {};
  if (urlSearch && urlSearch.length > 0) {
    const urlParams = urlSearch.split("&");
    urlParams.forEach((e: string) => {
      const obj = e.split("=");
      params[obj[0]] = obj[1];
    });
  }    
};

it says on the last line: Error:(17, 11) TS7017: Element implicitly has an 'any' type because type '{ foo?: number; bar?: number; }' has no index signature.

4

1 回答 1

2

你可以这样做:

const getFromUri = () => {
  const urlSearch = window.location.search.substring(1);

  // Always extract useful types
  type Params = { foo?: number; bar?: number };

  const params: Params = {};
  if (urlSearch && urlSearch.length > 0) {
    const urlParams = urlSearch.split("&");
    urlParams.forEach((e: string) => {
      // Assume key here
      const obj = <[keyof Params, string]>e.split("=");

      // Forgot to parse
      params[obj[0]] = parseInt(obj[1]);
    });
  }    
};

顺便说一句,不要这样做。只需使用URL类或 polyfill/库来获取搜索参数。

于 2018-03-27T09:56:57.653 回答