Skip to content

Generate types declarations #466

Open
@macabeus

Description

@macabeus

Currently we could define messages with variables:

hello = Hello { $name }
age = Your age is { $age }

and generating a bundle, we could use that on our code:

let hello = bundle.getMessage("hello")
console.log(bundle.formatPattern(hello.value, {name: "Anna"}))

let age = bundle.getMessage("age")
console.log(bundle.formatPattern(age.value, {age: "23"}))

But since there are lacking type informations, TS can't check if I'm writing all variables that message requires, or if I typed something wrong, as well as it's missing autocomplete.

bundle.formatPattern(hello.value); // I forgot to set the name
bundle.formatPattern(hello.value, {nam: 'Anna'}); // typo
bundle.formatPattern(hello.value, {age: 23}); // very bad!

We could improve even more if we could read the comments

# $name (String) - The user name
hello = Hello { $name }
bundle.formatPattern(hello.value, {name: 23}); // type error: should be string

On this small example, a valid type declaration would be:

type MessagesKey = 'welcome' | 'age'

type PatternArguments<T extends MessagesKey> = (
    T extends 'welcome'
        ? { name: string }
        :
    T extends 'age'
        ? { age: number }
        : never
)

export declare type Message<T> = {
    id: T;
    value: Pattern<T> | null;
    attributes: Record<string, Pattern<T>>;
};

export declare class FluentBundle {
  // inside of FluentBundle...

  getMessage<T extends MessagesKey>(id: T): Message<T>;
  formatPattern<T extends MessagesKey>(pattern: Pattern<T>, args?: PatternArguments<T>, errors?: Array<Error> | null): string;
}

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions