-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtest.ts
54 lines (40 loc) · 1.17 KB
/
test.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
// Definitions
interface MetaObject {
key: string
value: string | number
refs: string[]
}
type KeyMap<K = string> = Record<string, K>
type MappedMetaObject<K extends string | number | symbol = string> = Record<K, MetaObject>
export const extractMetaobjectFields = <T extends string | number | symbol>(keyMap: KeyMap<T>, metaObject: MetaObject[]) => {
const r = metaObject.reduce((acc, thisMetaObject) => {
if (thisMetaObject.key in keyMap) {
const key = keyMap[thisMetaObject.key]
acc[key] = thisMetaObject
}
return acc
}, {} as MappedMetaObject<T>)
return r
}
// Usage
// Here, fill in the KeyMap parameter first, it'll allow autocompletion on the object-
type VideoMappedKeys = 'url' | 'type'
const video = {
keys: {
a_a: "type",
c_c: "url"
} satisfies KeyMap<VideoMappedKeys>,
}
const ALL_META_DEFINITIONS = {
video
}
const meta: MetaObject[] = [
{
key: 'a_a',
value: 123,
refs: []
}
]
const videoMetaObject = extractMetaobjectFields(ALL_META_DEFINITIONS.video.keys, meta) // satisfies MappedMetaObject<VideoKeys>
console.log(videoMetaObject.type) // works well !
console.log(videoMetaObject.url) // works well !