Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I18N: Strongly typed sprintf #52985

Open
swissspidy opened this issue Jul 26, 2023 · 0 comments
Open

I18N: Strongly typed sprintf #52985

swissspidy opened this issue Jul 26, 2023 · 0 comments
Labels
[Package] i18n /packages/i18n [Type] Code Quality Issues or PRs that relate to code quality [Type] Enhancement A suggestion for improvement.

Comments

@swissspidy
Copy link
Member

What problem does this address?

I just stumbled upon https://hacklewayne.com/a-truly-strongly-typed-printf-in-typescript and was wondering whether a solution like this could be considered for @tannin/sprintf.

Right now with the existing JSDoc every arg needs to be a string, when in fact the values will be cast to ints and floats anyway depending on the format.

What is your proposed solution?

A strongly typed implementation could make this more robust.

This would also help catch issues where the number of arguments doesn't match the number of placeholders.

From that article:

type Specifiers = {
    's': string,
    'd': number,
    'b': boolean,
    'D': Date
};

type Spec = keyof Specifiers;

type Values<T extends string> = 
    T extends `${infer _}%${infer K}${infer Rest}`
    ? K extends Spec
        ? [ Specifiers[K], ...Values<Rest> ]
        : Values<`${K}${Rest}`>
    : [];

declare function sprintf<T extends string>(format: T, ...values: Values<T>): string;

sprintf('this is a %s and it is %d %wyears old, right?%b %D %i %f', 'Hackle', 20, true, new Date()); // ok
sprintf('Hello %s', 'John'); // ok
sprintf('Hello %s', 'John', 'Doe'); // not ok, too many arguments
sprintf('Hello %s', false); // not ok, wrong type

Note: this doesn't support named arguments yet.

Related

@swissspidy swissspidy added [Type] Enhancement A suggestion for improvement. [Type] Code Quality Issues or PRs that relate to code quality [Package] i18n /packages/i18n labels Jul 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Package] i18n /packages/i18n [Type] Code Quality Issues or PRs that relate to code quality [Type] Enhancement A suggestion for improvement.
Projects
None yet
Development

No branches or pull requests

1 participant