From fae07f67bc0caaba1041fe867aaacde350537de1 Mon Sep 17 00:00:00 2001 From: Raul Macarie Date: Thu, 29 Feb 2024 22:52:07 +0100 Subject: [PATCH] fix(t-utils): let negotiators infer the return type from usage --- packages/t-utils/source/negotiator.ts | 33 +++++++++++++++------------ 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/packages/t-utils/source/negotiator.ts b/packages/t-utils/source/negotiator.ts index ec08a75..1267658 100644 --- a/packages/t-utils/source/negotiator.ts +++ b/packages/t-utils/source/negotiator.ts @@ -1,32 +1,37 @@ import { filterMatches } from "@fluent/langneg"; -export type LocaleNegotiator = ( +const typedFilterMatches = filterMatches as < + Requested extends string, + Available extends string, +>( + requested: readonly Requested[], + available: readonly Available[], + strategy: "filtering" | "lookup" | "matching", +) => Available[]; + +export type LocaleNegotiator = < + Locale extends TypeParamLocale, +>( availableLocales: readonly Locale[], ) => Locale | undefined; -export type LocaleNegotiators = +export type LocaleNegotiators = | readonly [...(LocaleNegotiator | false)[], Locale] | readonly []; -type Algorithm = ( +type Algorithm = ( requestedLocales: readonly string[], - availableLocales: readonly string[], -) => string[]; + availableLocales: readonly Available[], +) => Available[]; export const lookup: Algorithm = (requestedLocales, availableLocales) => - filterMatches( - // @info `filterMatches` expects mutable arrays - Array.from(requestedLocales), - Array.from(availableLocales), - "lookup", - ); + typedFilterMatches(requestedLocales, availableLocales, "lookup"); export const negotiator: ( requestedLocales: readonly string[], algorithm: Algorithm, -) => LocaleNegotiator = - (requestedLocales, algorithm) => (availableLocales) => - algorithm(requestedLocales, availableLocales)[0]; +) => LocaleNegotiator = (requestedLocales, algorithm) => (availableLocales) => + algorithm(requestedLocales, availableLocales)[0]; export const browser = () => negotiator(globalThis.navigator?.languages ?? [], lookup);