Search code examples
typescriptindex-signature

Index signature with typescript


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.


Solution

  • 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.