简体   繁体   中英

How can I make a Record with union as its key type in TypeScript, from a function?

I have a function like below

const getQueryParams = (names) => {
  const urlParams = new URLSearchParams(window.location.search)
  return names.reduce((acc, curr) => {
    return {
       ...acc,
       [curr]: urlParams.get(curr),
    }
  }, {})
}

I'd like to set TS types in order to get the following type for the output of the above function.

const params: Record<'a'|'b', string> = getQueryParams(['a', 'b'])

Is such a thing possible? If so, how can I do it?

This seems to work.

type GetQueryParams = <T extends string>(args: T[]) => Record<T, string | null>

export const getQueryParams: GetQueryParams = names => {
  const urlParams = new URLSearchParams(window.location.search)
  return names.reduce((acc, curr) => {
    return {
      ...acc,
      [curr]: urlParams.get(curr),
    }
  }, {} as ReturnType<GetQueryParams>)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM