Skip to content

Commit 5fd342e

Browse files
author
Andy Hanson
committed
Include VariableDeclaration initializer as a candidate type
1 parent fdd86dd commit 5fd342e

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/services/codefixes/inferFromUsage.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,16 @@ namespace ts.codefix {
319319
case SyntaxKind.ElementAccessExpression:
320320
inferTypeFromPropertyElementExpressionContext(<ElementAccessExpression>node.parent, node, checker, usageContext);
321321
break;
322+
case SyntaxKind.VariableDeclaration: {
323+
const { name, initializer } = node.parent as VariableDeclaration;
324+
if (node === name) {
325+
if (initializer) { // This can happen for `var x = null;` which still has an implicit-any error.
326+
addCandidateType(usageContext, checker.getTypeAtLocation(initializer));
327+
}
328+
break;
329+
}
330+
}
331+
// falls through
322332
default:
323333
return inferTypeFromContextualType(node, checker, usageContext);
324334
}
@@ -512,7 +522,7 @@ namespace ts.codefix {
512522
return checker.getStringType();
513523
}
514524
else if (usageContext.candidateTypes) {
515-
return checker.getWidenedType(checker.getUnionType(map(usageContext.candidateTypes, t => checker.getBaseTypeOfLiteralType(t)), UnionReduction.Subtype));
525+
return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(t => checker.getBaseTypeOfLiteralType(t)), UnionReduction.Subtype));
516526
}
517527
else if (usageContext.properties && hasCallContext(usageContext.properties.get("then" as __String))) {
518528
const paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then" as __String).callContexts, /*isRestParameter*/ false, checker);

tests/cases/fourslash/codeFixInferFromUsage_all.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@
1717
//// if (!x) x = 2;
1818
////}
1919

20-
// TODO: GH#24168
21-
2220
verify.codeFixAll({
2321
fixId: "inferFromUsage",
2422
fixAllDescription: "Infer all types from usage",
@@ -32,7 +30,7 @@ function g(z: number) {
3230
return z * 2;
3331
}
3432
35-
let x: number = null;
33+
let x: number | null = null;
3634
function h() {
3735
if (!x) x = 2;
3836
}`,

0 commit comments

Comments
 (0)