0

I'm working on a simple (but hopefully type-safe) system that represents timeSlots as strings.

// example
const t1 = "|mon::10:30|";
const t2 = "|fri::20:00|";

So far I have managed to type these timeSlotStrings using string concatenation:

export type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
export type TimeSlot = "08:00" | "08:30" | "09:00" | "09:30" | "10:00" /*...*/ "19:30" | "20:00";

export type TimeSlotString = `$|${Weekday}::${TimeSlot}|`; // <- there you go!

const t1: TimeSlotString = "|mon::08:00|"; // OK! ✅
const t2: TimeSlotString = "|sat::17:30|"; // OK! ✅

But now I need to type the resulting string of concatenating TimeSlotString many times. The type should be called TimeSlotsConcat but I'm not sure this is possible, if it is, then what the syntax would look like?...

// example:
type TimeSlotsConcat = 🤨❓❓❓ // <- what type would satisfy s1 and s2?

const s1: TimeSlotsConcat = "|mon::10:30||tue::14:30||wed::08:00|";
const s2: TimeSlotsConcat = "|tue::11:00||tue::14:30||thu::18:00||fri::12:30|";

I tried using the TimeSlotString type recursively, but no luck...


type TimeSlotsConcat = "" | `${TimeSlotString}` | `${TimeSlotString}${TimeSlotsConcat}`;

//  ❌ ERROR: Type alias 'TimeSlotConcatStrings' circularly references itself.

So here goes the QUESTION: Is there a way to represent TimeSlotsConcat in typescript?

2
  • 1
    Why are you using string concatenation instead of arrays or some other collection type? Commented Feb 8, 2024 at 3:02
  • 1
    No, there is no specific type in TypeScript corresponding to that set of values. TypeScript unions can only represent a finite collection of types, and anything more than 10,000 members or so is going to give you problems. Your TimeSlotString has 175 members, a pair has 30,625 members which is already pushing the limits, and triplets are too much. The best you can do is write a generic validation type, like this playground link shoes. Does that fully address the question? If so I'll write up an answer explaining; if not, what am I missing? Commented Feb 8, 2024 at 3:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.