Skip to content

Commit 73b13b6

Browse files
authored
fixed function expression inference in binary operators (#472)
1 parent a30beba commit 73b13b6

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

src/TSHelper.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -509,11 +509,14 @@ export class TSHelper {
509509
// Expression assigned to declaration
510510
return checker.getTypeAtLocation(expression.parent.name);
511511

512-
} else if (ts.isBinaryExpression(expression.parent)
513-
&& expression.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken)
514-
{
515-
// Expression assigned to variable
516-
return checker.getTypeAtLocation(expression.parent.left);
512+
} else if (ts.isBinaryExpression(expression.parent)) {
513+
if (expression.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
514+
// Expression assigned to variable
515+
return checker.getTypeAtLocation(expression.parent.left);
516+
} else {
517+
// Other binary expressions
518+
return TSHelper.inferAssignedType(expression.parent, checker);
519+
}
517520

518521
} else if (ts.isAssertionExpression(expression.parent)) {
519522
// Expression being cast

test/unit/assignments.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,19 @@ export class AssignmentTests {
837837
+ "Overloads should either be all functions or all methods, but not both.");
838838
}
839839

840+
@TestCase("(this: void, s: string) => string")
841+
@TestCase("(this: any, s: string) => string")
842+
@TestCase("(s: string) => string")
843+
@Test("Function expression type inference in binary operator")
844+
public functionExpressionTypeInferenceInBinaryOp(funcType: string): void {
845+
const header = `declare const undefinedFunc: ${funcType};`;
846+
const code =
847+
`let func: ${funcType} = s => s;
848+
func = undefinedFunc || (s => s);
849+
return func("foo");`;
850+
Expect(util.transpileAndExecute(code, undefined, undefined, header)).toBe("foo");
851+
}
852+
840853
@TestCase("s => s")
841854
@TestCase("(s => s)")
842855
@TestCase("function(s) { return s; }")

0 commit comments

Comments
 (0)