Add related diagnostic to "used before defined" if type is a function that returns a union with undefined (#33171)

* Add "use before defined" diagnostic

* Make "use before defined" diagnostic as related information to TS2454

* Add baseline tests for "use before defined"

* Add test for type alias union with undefined for "use before defined" diagnostic

* Update baselines
This commit is contained in:
Ozair Patel
2019-11-04 17:53:31 -05:00
committed by Orta
parent 47ec514cf4
commit be960fa356
7 changed files with 369 additions and 1 deletions
+20 -1
View File
@@ -20190,7 +20190,26 @@ namespace ts {
}
}
else if (!assumeInitialized && !(getFalsyFlags(type) & TypeFlags.Undefined) && getFalsyFlags(flowType) & TypeFlags.Undefined) {
error(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
const diag = error(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
// See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined
// they may have meant to specify the type as (() => T1 | ...) | undefined
// This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of
// the union is `undefined`
if (type.symbol && type.symbol.declarations.length === 1 && isFunctionTypeNode(type.symbol.declarations[0])) {
const funcTypeNode = <FunctionTypeNode>type.symbol.declarations[0];
const returnType = getReturnTypeFromAnnotation(funcTypeNode);
if (returnType && returnType.flags & TypeFlags.Union) {
const unionTypes = (<UnionTypeNode>funcTypeNode.type).types;
if (unionTypes && unionTypes[unionTypes.length - 1].kind === SyntaxKind.UndefinedKeyword) {
const parenedFuncType = getMutableClone(funcTypeNode);
// Highlight to the end of the second to last constituent of the union
parenedFuncType.end = unionTypes[unionTypes.length - 2].end;
addRelatedInfo(diag, createDiagnosticForNode(parenedFuncType, Diagnostics.Did_you_mean_to_parenthesize_this_function_type));
}
}
}
// Return the declared type to reduce follow-on errors
return type;
}
+4
View File
@@ -1047,6 +1047,10 @@
"category": "Error",
"code": 1359
},
"Did you mean to parenthesize this function type?": {
"category": "Error",
"code": 1360
},
"The types of '{0}' are incompatible between these types.": {
"category": "Error",