-
Notifications
You must be signed in to change notification settings - Fork 0
/
13 ~ TemplateLiterals.ts
63 lines (53 loc) · 1.34 KB
/
13 ~ TemplateLiterals.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const greet = (name: string) => {
// "Template literal":
return `Hello ${name}`
}
/*
*
*
*
*/
type Presenter = "Jeroen" | "Jens"
type Style = "boring" | "interesting"
type StyledPresenters = `${Style} ${Presenter}`
/*
*
*
*
*/
type StyleFrom<Presenter> = Presenter extends `${infer Style} ${string}`
? Style
: never
type NameFrom<Presenter> = Presenter extends `${string} ${infer Name}`
? Name
: never
type A = StyleFrom<"boring Jens">
type B = NameFrom<"boring Jens">
/*
*
*
*
*/
const 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"],
} as const
type Menu = typeof menu
type MainIngredients = {
[Day in keyof Menu]: Menu[Day][number] extends `${infer T} and ${string}`
? T
: never
}
// Sometimes it helps to write it in pieces:
type MainIngredient<MenuItem> = MenuItem extends `${infer Main} and ${string}`
? Main
: never
type PossibleValues<T extends readonly any[]> = T[number]
type MainIngredients2 = {
[Day in keyof Menu]: MainIngredient<PossibleValues<Menu[Day]>>
}