Skip to content

Generate strictly typed definition of TFunction from own i18next-locale file

Notifications You must be signed in to change notification settings

kogai/typed_i18n

Repository files navigation

typed_i18n

npm version CircleCI

Generate strictly typed definition of TFunction from own i18next dictionary file.

It generate from

{
  "en": {
    "translation": {
      "foo": {
        "bar": "some text",
        "buzz": 999
      }
    }
  }
}

as

// @flow
declare function t(_: "foo"): {
  +bar: string,
  +buzz: number
};
declare function t(_: "foo.bar"): string;
declare function t(_: "foo.buzz"): number;

export type TFunction = typeof t;

or

declare namespace typed_i18n {
  interface TFunction {
    t(_: "foo"): {
      +bar: string,
      +buzz: number,
    };
    t(_: "foo.bar"): string;
    t(_: "foo.buzz"): number;
  }
}
export = typed_i18n;

then if you use TFunction like below, type-checker warn you function call by invalid path

// @flow

import type { TFunction } from "./locale.translation"; // Definition file generated

declare var t: TFunction;

// Those are ok
const x: { bar: string, buzz: number } = t("foo");
const x1: string = x.bar;
const x2: number = x.buzz;
// Expect error
const x3 = x.buzzz;

// Expect error
const y = t("fooo");

// Those are also strictly typed too
const z1: string = t("foo.bar");
const z2: number = t("foo.buzz");

Usage

# Basic usage
$ typed_i18n -i path/to/your.json -o path/to/out/dir

# Support also typescript
$ typed_i18n -i path/to/your.json -o path/to/out/dir -l typescript

# You can specify namespaces instead of default "translation"
$ typed_i18n -i path/to/your.json -o path/to/out/dir -n translate -n my-namespace -n other-namespace

About

Generate strictly typed definition of TFunction from own i18next-locale file

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •