-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.js
66 lines (57 loc) · 1.72 KB
/
util.js
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
function mapType(type, t) {
// TODO: directiveLiteral
switch (type) {
case 'NumericLiteral':
case 'TSNumberKeyword':
case 'number':
return t.tsNumberKeyword();
case 'StringLiteral':
case 'TSStringKeyword':
case 'string':
return t.tsStringKeyword();
case 'BooleanLiteral':
case 'TSBooleanKeyword':
case 'boolean':
return t.tsBooleanKeyword();
case 'NullLiteral':
case 'TSNullKeyword':
case 'null':
return t.tsNullKeyword();
default:
return t.tsAnyKeyword();
}
}
function multiTypeArray(elements, t) {
let types = new Set();
elements.map(x => types.add(mapType(x.type, t)));
return Array.from(types);
}
function typesDiffer(elements) {
const type = elements[0].type;
for (let i = 1; i < elements.length; ++i) {
if (elements[i].type != type) return true;
}
return false;
}
function getType(node, t) {
const isArray = node.type === 'ArrayExpression';
if (isArray) return t.tsTupleType(multiTypeArray(node.elements, t));
return mapType(node.type, t);
}
function addTypeAnnotation(node, typeAnnotation, t) {
if (!typeAnnotation) return; // the user said "skip"
if (node.type === 'FunctionDeclaration')
node.returnType = t.tsTypeAnnotation(typeAnnotation);
else node.typeAnnotation = t.tsTypeAnnotation(typeAnnotation);
}
// extentions
String.prototype.insert = function(index, string) {
if (index > 0)
return (
this.substring(0, index) +
string +
this.substring(index, this.length)
);
return string + this;
};
module.exports = { getType, addTypeAnnotation };