lingui / lingui/js-lingui

Strictly typed values alongside message with variables

Open
#2,206 5 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
5.9k
Forks
457
Avg merge
1d 23h
Merged PRs (30d)
16

Description

Problem Description

Currently if you use MessageDescriptors directly

i18n._({
  id: "uxV9Xq",
  message: "Hey {firstName}!",
  values: { firstname: "Alice" },
})

Values will be typed as

values?: Record<string, unknown>
Proposed Solution

From the context it would be possible to infer the variables and strictly type the values.

type ExtractVariables<T extends string> =
  T extends `${string}{${infer Variable}}${infer Rest}`
    ? Variable | ExtractVariables<Rest>
    : never;

type HasVariables<T extends string> = ExtractVariables<T> extends never
  ? false
  : true;

type MessageDescriptor<T extends string = string> = {
  id: string;
  comment?: string;
  message?: T;
} & (HasVariables<T> extends true
  ? {
      values: {
        [K in ExtractVariables<T>]: unknown;
      };
    }
  : {
      values?: Record<string, unknown>;
    });

// ...

declare class I18n extends EventEmitter<Events> {
  // ...

  _<T extends string = string>(descriptor: MessageDescriptor<T>): string;

  // ...
}

And in the above example that would be

values: {
  firstName: unknown;
}

This would prevent missing values or adding extraordinary keys to variable values. It helps detect that firstname was incorrectly capitalized and missing

Alternatives Considered

Keep types loose and unsafe

Additional Context

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the TypeScript definitions for MessageDescriptor and the I18n._ method shown in the proposal. Trace how message descriptors and values are currently typed, then verify that variables inferred from the message require matching value keys while messages without variables retain optional values.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
internationalization
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.