Skip to content

Commit

Permalink
feature(types): add ability to type translation keys
Browse files Browse the repository at this point in the history
This is a first step towards solving i18next#1504
It allows you to type your translation keys freely. Which allows you to type them using the template literals of Typescript 4.1 for nested keys.
  • Loading branch information
pierpo committed Dec 8, 2020
1 parent ba564b3 commit 2a650cb
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions index.d.ts
Expand Up @@ -2,9 +2,23 @@ export interface FallbackLngObjList {
[language: string]: string[];
}

export type FallbackLng = string | string[] | FallbackLngObjList | ((code:string) => string | string[] | FallbackLngObjList);
/**
* Extend this with a 'keys' key where you can add all the available translation keys
*/
export interface TranslationKeys {}

export type FallbackLng =
| string
| string[]
| FallbackLngObjList
| ((code: string) => string | string[] | FallbackLngObjList);

export type FormatFunction = (value: any, format?: string, lng?: string, options?: InterpolationOptions & { [key: string]: any }) => string;
export type FormatFunction = (
value: any,
format?: string,
lng?: string,
options?: InterpolationOptions & { [key: string]: any },
) => string;

export interface InterpolationOptions {
/**
Expand Down Expand Up @@ -639,7 +653,7 @@ export type Callback = (error: any, t: TFunction) => void;
* Uses similar args as the t function and returns true if a key exists.
*/
export interface ExistsFunction<
TKeys extends string = string,
TKeys extends TFunctionKeys = Keys,
TInterpolationMap extends object = StringMap
> {
(key: TKeys | TKeys[], options?: TOptions<TInterpolationMap>): boolean;
Expand All @@ -650,13 +664,18 @@ export interface WithT {
t: TFunction;
}

/**
* Gets the defined translation keys if they have been overridden, 'string' type otherwise
*/
type Keys = TranslationKeys['keys'] extends string ? TranslationKeys['keys'] : string;

export type TFunctionResult = string | object | Array<string | object> | undefined | null;
export type TFunctionKeys = string | TemplateStringsArray;
export interface TFunction {
// basic usage
<
TResult extends TFunctionResult = string,
TKeys extends TFunctionKeys = string,
TKeys extends TFunctionKeys = Keys,
TInterpolationMap extends object = StringMap
>(
key: TKeys | TKeys[],
Expand All @@ -665,7 +684,7 @@ export interface TFunction {
// overloaded usage
<
TResult extends TFunctionResult = string,
TKeys extends TFunctionKeys = string,
TKeys extends TFunctionKeys = Keys,
TInterpolationMap extends object = StringMap
>(
key: TKeys | TKeys[],
Expand Down

0 comments on commit 2a650cb

Please sign in to comment.