resolve-accept-language/resolve-accept-language

Improve TypeScript type inference for string values

Closed this issue · 3 comments

iiroj commented

Hello,

thank you for this very useful package! It would be awesome if the type definitions supported a bit nicer inferring of return values. This way one could use literal string values.

Based on my testing something like this in resolveAcceptLanguage would already help:

https://github.com/Avansai/resolve-accept-language/blob/07a8a3292358790009ae6f47b06c0087ed76cb02/src/resolve-accept-language.ts#L113-L117

const resolveAcceptLanguage = <TLocale extends string>(
  acceptLanguageHeader: string,
  locales: TLocale[],
  defaultLocale: TLocale
): TLocale => {

It would allow type inference like:

Screenshot 2023-05-08 at 13 27 07

Thanks for the proposal @iiroj

I made some small modifications that I think will make the syntax even simpler:

    const locales = ['fr-CA', 'en-CA', 'it-IT', 'pl-PL'] as const
    resolveAcceptLanguage('fr-CA,en-CA,it-IT', locales, locales[0])

Details here: d40083f

Changes available in version 1.5.5: https://github.com/Avansai/resolve-accept-language/releases/tag/v1.1.55

iiroj commented

Hello,

thanks for the update! It looks like the return type is still string, should it be TLocales[number] instead?

https://github.com/Avansai/resolve-accept-language/blob/7deeb6614357dfc3463ce11ca1fd0ff0b3d4ac85/src/resolve-accept-language.ts#L117

My bad you're right @iiroj - the change is available in version 1.1.56

Thanks