Search code examples
typescriptfunctionobjecttypes

What is the best practice for returning type when the function is making object based on string?


I have the follow function that is retuning an object when a string is provided. I defined as any but I wonder if exists a better type or generic type even when the object structure is unknow

This is the function:

const decodeParameters = (params: string): any => {
  return decodeURI(params)
    .split('&')
    .reduce((result, current) => {
      const [key, value] = current.split('=');

      result[key] = value;

      return result;
    }, {});
}

// https://stackblitz.com/edit/typescript-drs5f6?file=index.ts
const queryParametersObj1 = decodeParameters('file=index.ts');
console.log(queryParametersObj1)

Output:

{file: "index.ts"}

Live sample.


Solution

  • Your return type is Record<string, string | undefined> since you may have an object that can have any key, but the values are always string or undefiend.

    
    const decodeParameters = (params: string): Record<string, string| undefined> => {
      return decodeURI(params)
        .split('&')
        .reduce((result, current) => {
          const [key, value] = current.split('=');
    
          result[key] = value;
    
          return result;
        }, {});
    };
    
    const queryParametersObj2 = decodeParameters(
      'q=return+unknow+object+in+method+typescript+what+type&rlz=1C1GCER_en&oq=return+unknow+object+in+method+typescript+what+type&gs_lcrp=EgZjaHJvbWUyBggAEEUYOdIBCTEyNjAwajBqN6gCALACAA&sourceid=chrome&ie=UTF-8'
    );
    
    //here we have type safety on the value since it is a string
    if (queryParametersObj2['q'] !== undefined) {
      console.log(queryParametersObj2['q'].split('+'));
    }
    
    

    Here is a working fork on your example