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.

MrMamen
  • 359
  • 2
  • 14

1 Answers1

2

You can do something like this:

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

By the way, don't do this. Just use the URL class or a polyfill/library to get search params.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • The standard URL class already has all you need, try: `Array.from(new URL(document.location.href).searchParams)` – H.B. Mar 27 '18 at 10:31