Skip to content

Commit f7beaac

Browse files
HerrCai0907dcodeIO
andauthored
fix: infer return type in implicit return arrow function (#2433)
Co-authored-by: dcode <[email protected]>
1 parent 6968448 commit f7beaac

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/resolver.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,9 @@ import {
7676
isTypeOmitted,
7777
FunctionExpression,
7878
NewExpression,
79-
ArrayLiteralExpression
79+
ArrayLiteralExpression,
80+
ArrowKind,
81+
ExpressionStatement
8082
} from "./ast";
8183

8284
import {
@@ -2615,7 +2617,25 @@ export class Resolver extends DiagnosticEmitter {
26152617
/** How to proceed with eventual diagnostics. */
26162618
reportMode: ReportMode = ReportMode.REPORT
26172619
): Type | null {
2618-
return this.resolveFunctionType(node.declaration.signature, ctxFlow.actualFunction, ctxFlow.contextualTypeArguments, reportMode);
2620+
const declaration = node.declaration;
2621+
const signature = declaration.signature;
2622+
const body = declaration.body;
2623+
let functionType = this.resolveFunctionType(signature, ctxFlow.actualFunction, ctxFlow.contextualTypeArguments, reportMode);
2624+
if (
2625+
functionType &&
2626+
declaration.arrowKind != ArrowKind.NONE &&
2627+
body && body.kind == NodeKind.EXPRESSION &&
2628+
isTypeOmitted(signature.returnType)
2629+
) {
2630+
// (x) => ret, infer return type accordingt to `ret`
2631+
const expr = (<ExpressionStatement>body).expression;
2632+
const type = this.resolveExpression(expr, ctxFlow, ctxType, reportMode);
2633+
if (type) {
2634+
let signatureReference = assert(functionType.getSignature());
2635+
signatureReference.returnType = type;
2636+
}
2637+
}
2638+
return functionType;
26192639
}
26202640

26212641
// ==================================================== Elements =====================================================

tests/compiler/std/array.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -780,7 +780,7 @@ var i: i32;
780780
// Array#map ///////////////////////////////////////////////////////////////////////////////////////
781781

782782
{
783-
let newArr = arr.map<f32>((value: i32) => <f32>value);
783+
let newArr = arr.map((value: i32, index: i32, arr: Array<i32>) => <f32>value);
784784
assert(newArr.length == 4);
785785
assert(newArr[0] == <f32>arr[0]);
786786

0 commit comments

Comments
 (0)