amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.37k stars 214 forks source link

Typesafe Global formats #1340

Closed dBianchii closed 1 week ago

dBianchii commented 1 week ago

Is your feature request related to a problem? Please describe.

Global formats are awesome. It's great to help achieve consistency in my application. However, if I create these global settings for the formatter, they won't be typesafe format.dateTime(new Date('2020-11-20T10:36:01.516Z'), 'short'); // => the second parameter requested is always of type 'string'.

Describe the solution you'd like

I'd like for the formatter to be of a narrower type, based on the template literal values of what I added in my config

Describe alternatives you've considered

In my global.d.ts file:

import { formats as myFormats } from "@kdx/locales";
declare module "use-intl" {
  function createFormatter({
    _formatters: formatters,
    formats,
    locale,
    now: globalNow,
    onError,
    timeZone: globalTimeZone,
  }: Props): {
    dateTime: (
      value: Date | number,
      formatOrOptions?: keyof typeof myFormats.dateTime | DateTimeFormatOptions,
    ) => string;
  };
}

my @kdx/locales file:

import type { Formats } from "use-intl";
export const formats = {
  dateTime: {
    extensive: {
      day: "2-digit",
      month: "long",
      year: "numeric",
      hour: "numeric",
      minute: "numeric",
    },
  },
} as const satisfies Partial<Formats> | undefined;

As you can see, this ALMOST works. I am extending/rewriting the return type of createFormatter from use-intl. In my code, now the dateFormat function is typesafe. image

However, there is a big problem: since I completely redeclared the return type of createFormatter, now I all of the typesafety for all other methods are gone, and only this function is declared inside it :stuck_out_tongue:

amannn commented 1 week ago

I absolutely agree, would love to have this but haven't found the time yet to look into this. There's already an issue open at https://github.com/amannn/next-intl/issues/1112, I'll close this in favor of the former one.

Let me know in case you'd be interested in helping out with this!

dBianchii commented 1 week ago

Sorry, I wasn't able to find this issue. I usually try to search for similar issues before posting!