-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
interface.ts
70 lines (57 loc) · 2.01 KB
/
interface.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
64
65
66
67
68
69
70
import type { SupportedDataTypes } from "./data_types.ts";
import type { PropertyPrototype, SchemaPrototype } from "./schema.ts";
type IsOptional<Property extends PropertyPrototype> = Property extends {
"@optional": true;
} ? true
: false;
type IsArray<Property extends PropertyPrototype> = Property extends {
"@array": true;
} ? true
: false;
type IsMultilang<Property extends PropertyPrototype> = Property extends {
"@multilang": true;
} ? true
: false;
type ValidPropertyDefinition = PropertyPrototype | string;
type ConvertPropertyType<T extends PropertyPrototype> = T extends {
"@context": SchemaPrototype;
}
// embedded schema
? SchemaInterface<T["@context"]>
// type specified
: T extends { "@type": unknown } ? T["@type"] extends keyof SupportedDataTypes
// type is built-int
? SupportedDataTypes[T["@type"]]
// type is invalid
: never
// no type -> defaults to string
: string;
type ConvertPropertyOptional<T extends PropertyPrototype> =
IsOptional<T> extends true ? ConvertPropertyType<T> | undefined
: ConvertPropertyType<T>;
type ConvertPropertyArray<T extends PropertyPrototype> = IsArray<T> extends true
? ConvertPropertyType<T>[]
: ConvertPropertyOptional<T>;
type ConvertPropertyMultilang<T extends PropertyPrototype> =
IsMultilang<T> extends true
? IsArray<T> extends true ? Record<string, ConvertPropertyType<T>[]>
: Record<string, ConvertPropertyType<T>>
: ConvertPropertyArray<T>;
type ConvertPropertyObject<T extends PropertyPrototype> =
ConvertPropertyMultilang<T>;
type ConvertProperty<T extends ValidPropertyDefinition> = T extends
PropertyPrototype ? ConvertPropertyObject<T> : string;
export type SchemaInterfaceIdentity = {
$id: string;
};
export type SchemaInterfaceType = {
$type: string[];
};
export type SchemaInterface<T extends SchemaPrototype> =
& {
[X in Exclude<keyof T, "@type">]: T[X] extends ValidPropertyDefinition
? ConvertProperty<T[X]>
: never;
}
& SchemaInterfaceIdentity
& SchemaInterfaceType;