-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocales.ts
59 lines (46 loc) · 1.08 KB
/
locales.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
const locales = {
en_us: {
hello: "Hi {user}",
greetings: {
morning: "Good morning {user}",
evenings: "Good evening {user}",
casual: {
morning: "Yo, happy morning",
afternoon: "Yolo",
},
},
},
}
type LocalMap = typeof locales
type LocaleName = keyof LocalMap
type Locale = LocalMap[LocaleName]
type PathInto<T extends Record<string, any>> = keyof {
[K in keyof T as T[K] extends string
? K
: T[K] extends Record<string, any>
? `${K & string}.${PathInto<T[K]> & string}`
: never]: any
}
type foo = PathInto<Locale>
function get(
object: Record<string, unknown>,
path: Array<string>,
index = 0
): string {
const key = path[index]
if (key === undefined) {
return ""
}
const result = object[key]
if (result === undefined) {
return ""
}
if (typeof result === "string") {
return result
}
return get(Object(result), path, index + 1)
}
const currentLocales: LocaleName = "en_us"
export function t(key: PathInto<Locale>): string {
return get(locales[currentLocales], key.split("."))
}