-
Notifications
You must be signed in to change notification settings - Fork 0
/
27 ~ Exercise: DaysWith - IngredientsPerDay - Solution.ts
45 lines (40 loc) · 1.34 KB
/
27 ~ Exercise: DaysWith - IngredientsPerDay - Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Task: Given an ingredient, say on which day you can eat it
// To help: start with figuring out which ingredients are used on which days
type Menu = {
Monday: ["Steak and lettuce", "Codd and tomatoes"]
Tuesday: ["Chicken and carrots", "Peas and carrots"]
Wednesday: ["Fish and chips", "Turkey and stuffing"]
Thursday: ["Sushi and rice", "Wok and noodles"]
Friday: ["Lamb and tomatoes", "Salmon and cheese"]
Saturday: ["Spaghetti and pesto", "Penne and arrabiata"]
Sunday: ["Fries and ketchup", "Fries and mayonnaise"]
}
/*
*
*
*
*/
type IngredientsOn<Day extends keyof Menu> =
Menu[Day][number] extends `${infer Main} and ${infer Side}`
? Main | Side
: never
// type IngredientsOnMonday = "Steak" | "lettuce" | "Codd" | "tomatoes"
type IngredientsOnMonday = IngredientsOn<"Monday">
// type IngredientsOnSunday = "Fries" | "ketchup" | "mayonnaise"
type IngredientsOnSunday = IngredientsOn<"Sunday">
/*
*
*
*
*/
type DaysWith<I extends string> = {
[Day in keyof Menu]: I extends IngredientsOn<Day> ? Day : never
}[keyof Menu]
// type DaysWithSteak = "Monday"
type DaysWithSteak = DaysWith<"Steak">
// type DaysWithFries = "Sunday"
type DaysWithFries = DaysWith<"Fries">
// type DaysWithTomatoes = "Monday" | "Friday"
type DaysWithTomatoes = DaysWith<"tomatoes">
// type DaysWithHummus = never
type DaysWithHummus = DaysWith<"hummus">