This repository has been archived by the owner on Dec 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
TypeValidator.ts
133 lines (109 loc) · 2.41 KB
/
TypeValidator.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*!
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT
*/
/**
* A descriptor is simply a JSON tree that either has an actual value or a type that identifies what the expect type should be at that leaf in the tree.
*
* var descriptor = {
* a : Object,
* b : String,
* c : {
* d : true ,
* e : Array,
* f : []
* },
* g : "literal"
* }
*/
import {Type, TypeInfo} from "./Types";
import {areEqual} from "./Compare";
import __extendsImport from "../extends";
// noinspection JSUnusedLocalSymbols
const __extends = __extendsImport;
export class TypeInfoHelper extends TypeInfo
{
private _value:any;
constructor(value:any)
{
super(value, self=>self._value = value);
}
contains<TDescriptor>(descriptor:any):this is TDescriptor
{
let value = this._value;
if(value===descriptor)
return true;
switch(descriptor)
{
case Function:
return this.isFunction;
case Object:
return this.isObject;
case Array:
return this.isArray;
case String:
return this.isString;
case Number:
return this.isNumber;
case Boolean:
return this.isBoolean;
}
if(this.type!= typeof descriptor || this.isPrimitive && !areEqual(value, descriptor))
return false;
// Check array contents and confirm intersections.
if(this.isArray && Type.isArrayLike(descriptor))
{
let max = Math.min(descriptor.length, value.length);
for(let i = 0; i<max; i++)
{
if(areInvalid(value[i], descriptor[i]))
return false;
}
return true;
}
if(this.isObject)
{
let targetKeys = Object.keys(value);
let dKeys = Object.keys(descriptor);
// Quick check...
if(dKeys.length>targetKeys.length)
return false;
// Quick check #2...
for(let key of dKeys)
{
if(targetKeys.indexOf(key)== -1)
return false;
}
// Final pass with recursive...
for(let key of dKeys)
{
if(areInvalid(value[key], descriptor[key]))
return false;
}
}
return true;
}
}
function areInvalid(v:any, d:any)
{
if(!areEqual(v, d))
{
let memberType = new TypeInfoHelper(v);
if(!memberType.contains(d))
return true;
}
return false;
}
export class TypeValidator<T>
{
constructor(private readonly _typeDescriptor:any)
{
Object.freeze(this);
}
isSubsetOf(o:any):o is T
{
return (new TypeInfoHelper(o))
.contains(this._typeDescriptor);
}
}
export default TypeValidator;