Skip to content

Commit 906f69d

Browse files
committed
Also infer type from const initializer
Infer the type for statements like: ```js const x = 42; ``` same as: ```js const x: number = 42; ```
1 parent 4f4877f commit 906f69d

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

lib/infer/type.js

+9
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ var finders = require('./finders'),
55
flowDoctrine = require('../flow_doctrine'),
66
t = require('babel-types');
77

8+
var constTypeMapping = {
9+
'BooleanLiteral': {type: 'BooleanTypeAnnotation'},
10+
'NumericLiteral': {type: 'NumberTypeAnnotation'},
11+
'StringLiteral': {type: 'StringTypeAnnotation'}
12+
};
13+
814
/**
915
* Infers type tags by using Flow type annotations
1016
*
@@ -27,6 +33,9 @@ module.exports = function () {
2733
switch (n.type) {
2834
case 'VariableDeclarator':
2935
type = n.id.typeAnnotation;
36+
if (!type && comment.kind === 'constant') {
37+
type = constTypeMapping[n.init.type];
38+
}
3039
break;
3140
case 'ClassProperty':
3241
type = n.typeAnnotation;

test/lib/infer/type.js

+24
Original file line numberDiff line numberDiff line change
@@ -107,5 +107,29 @@ test('inferType', function (t) {
107107
type: 'NameExpression'
108108
});
109109

110+
t.deepEqual(evaluate(
111+
'/** */' +
112+
'const x = 42;'
113+
).type, {
114+
name: 'number',
115+
type: 'NameExpression'
116+
});
117+
118+
t.deepEqual(evaluate(
119+
'/** */' +
120+
'const x = "abc";'
121+
).type, {
122+
name: 'string',
123+
type: 'NameExpression'
124+
});
125+
126+
t.deepEqual(evaluate(
127+
'/** */' +
128+
'const x = true;'
129+
).type, {
130+
name: 'boolean',
131+
type: 'NameExpression'
132+
});
133+
110134
t.end();
111135
});

0 commit comments

Comments
 (0)