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

Add Ordinal type #1025

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open

Conversation

ohansFavour
Copy link
Contributor

This PR adds a new Ordinal type that creates a type that converts a number literal type to its ordinal string representation.

@som-sm som-sm changed the title Add Ordinal type Add Ordinal type Dec 31, 2024
@sindresorhus
Copy link
Owner

What's the practical use-case for this at the type-level?

@ohansFavour
Copy link
Contributor Author

@sindresorhus The Ordinal type has some practical use cases at the type level, particularly when working with type-safe string templates. For example:

  • Type-safe date formatting libraries:
type DateFormat<D extends number> = `MMMM ${Ordinal<D>}, YYYY`;
type FormattedDate = DateFormat<3>; // "MMMM 3rd, YYYY"
  • Achievement systems that need compile-time guarantees for rank formatting:
type AchievementLevel<N extends number> = {
    rank: Ordinal<N>;
    unlockMessage: `You've reached ${Ordinal<N>} place!`;
    badge: `${Ordinal<N>}_place_badge`;
};

// Ensures correct formatting at compile time
type GoldAchievement = AchievementLevel<1>;
// {rank: "1st", unlockMessage: "You've reached 1st place!", badge: "1st_place_badge"}
  • Educational/Quiz application types where question ordering is semantically important:
type QuizQuestion<N extends number> = {
    prompt: `${Ordinal<N>} attempt: Choose the correct answer`;
    feedback: {
        success: `Correct on your ${Ordinal<N>} try!`;
        failure: N extends 3 
            ? "Final attempt failed. Please review the material."
            : `Try again (${Ordinal<N extends number ? N + 1 : never>} attempt)`;
    };
};

// Automatically generates correct ordinal messages
type SecondAttempt = QuizQuestion<2>;
/* Results in:
{
    prompt: "2nd attempt: Choose the correct answer",
    feedback: {
        success: "Correct on your 2nd try!",
        failure: "Try again (3rd attempt)"
    }
}
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants