Skip to content

fix: infer return type in implicit return arrow function #2433

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ import {
isTypeOmitted,
FunctionExpression,
NewExpression,
ArrayLiteralExpression
ArrayLiteralExpression,
ArrowKind,
ExpressionStatement
} from "./ast";

import {
Expand Down Expand Up @@ -2613,7 +2615,25 @@ export class Resolver extends DiagnosticEmitter {
/** How to proceed with eventual diagnostics. */
reportMode: ReportMode = ReportMode.REPORT
): Type | null {
return this.resolveFunctionType(node.declaration.signature, ctxFlow.actualFunction, ctxFlow.contextualTypeArguments, reportMode);
const declaration = node.declaration;
const signature = declaration.signature;
const body = declaration.body;
let functionType = this.resolveFunctionType(signature, ctxFlow.actualFunction, ctxFlow.contextualTypeArguments, reportMode);
if (
functionType &&
declaration.arrowKind != ArrowKind.NONE &&
body && body.kind == NodeKind.EXPRESSION &&
isTypeOmitted(signature.returnType)
) {
// (x) => ret, infer return type accordingt to `ret`
const expr = (<ExpressionStatement>body).expression;
const type = this.resolveExpression(expr, ctxFlow, ctxType, ReportMode.SWALLOW);
if (type) {
let signatureReference = assert(functionType.getSignature());
signatureReference.returnType = type;
}
}
return functionType;
}

// ==================================================== Elements =====================================================
Expand Down
2 changes: 1 addition & 1 deletion tests/compiler/std/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -780,7 +780,7 @@ var i: i32;
// Array#map ///////////////////////////////////////////////////////////////////////////////////////

{
let newArr = arr.map<f32>((value: i32) => <f32>value);
let newArr = arr.map((value: i32, index: i32, arr: Array<i32>) => <f32>value);
assert(newArr.length == 4);
assert(newArr[0] == <f32>arr[0]);

Expand Down