sveltekit-i18n / lib

Internationalization library built for SvelteKit.
MIT License
505 stars 33 forks source link

Better typescript support #60

Open jarda-svoboda opened 2 years ago

jarda-svoboda commented 2 years ago

Currently, there is no type checking for translation keys, which can result in typos. Also payload types have to be defined manually and options contain all definitions for all modifiers at once.

sveltekit-i18n should provide a plugin/CLI based way how to deal with that, fetching sources and generating appropriate types automatically. payload and options types should be inferred from translations dynamically according to specified key.

bartduisters commented 1 year ago

An example to get rid of the TypeScript warning in the template.

<div>{@html $t('common.some-key', { link: 'https://code-coaching.dev' })}</div>

👆 This would show a TypeScript error on the link: 'some string' part.

👇 This is the manual definition that @jarda-svoboda is talking about.

import type { Config } from 'sveltekit-i18n';
import i18n from 'sveltekit-i18n';

interface Params {
  link: string;
  // add more parameters that are used here
}

const config: Config<Params> = ({
  loaders: [
    {
      locale: 'en',
      key: 'common',
      loader: async () => (
        await import('./en/common.json')
      ).default,
    },
    {
      locale: 'nl',
      key: 'common',
      loader: async () => (
        await import('./nl/common.json')
      ).default,
    },
  ],
});

export const { t, locale, locales, loading, loadTranslations } = new i18n(config);
boian-ivanov commented 1 year ago

I've been having this issue with a @ts-ignore bandaid for quite a while, until today where I started searching if we can modify the PayloadDefault, but this has helped immensely. Thanks @bartduisters! 👏 Although to be fair, I'm not sure how good that is, especially in bigger projects, where you might have a list of 100+ params that you may need to use. I'd be curious if it's even worth having that sort of type def, especially this deep, or potentially a way to set the type upon usage of the $t() function. Not really sure how, but an improvement on it might be needed.

MaxSvargal commented 7 months ago

It's good to have generated typings for each intl mesage.