fix(isolated-declarations): inferring an incorrect return type when there is an arrow function inside a function (#3768)

This commit is contained in:
Dunqing 2024-06-19 15:43:15 +00:00
parent 315f9ad9bf
commit 8ce794d740
3 changed files with 18 additions and 6 deletions

View file

@ -1,7 +1,7 @@
use oxc_ast::{
ast::{
BindingIdentifier, Expression, Function, FunctionBody, ReturnStatement, TSType,
TSTypeAliasDeclaration, TSTypeName, TSTypeQueryExprName,
ArrowFunctionExpression, BindingIdentifier, Expression, Function, FunctionBody,
ReturnStatement, TSType, TSTypeAliasDeclaration, TSTypeName, TSTypeQueryExprName,
},
AstBuilder, Visit,
};
@ -138,6 +138,10 @@ impl<'a> Visit<'a> for FunctionReturnType<'a> {
// We don't care about nested functions
}
fn visit_arrow_expression(&mut self, _expr: &ArrowFunctionExpression<'a>) {
// We don't care about nested functions
}
fn visit_return_statement(&mut self, stmt: &ReturnStatement<'a>) {
self.return_statement_count += 1;
if self.return_statement_count > 1 {

View file

@ -4,7 +4,7 @@ function foo() {
// inferred type is number
function bar() {
if (true) {
if (a) {
return;
}
return 1;
@ -12,9 +12,16 @@ function bar() {
// inferred type is number | undefined
function baz() {
if (true) {
if (a) {
return null;
}
return 1;
}
// We can't infer return type if there are multiple return statements with different types
// We can't infer return type if there are multiple return statements with different types
function qux() {
const a = (() => {
return 1;
})();
return `Hello, world!`;
}

View file

@ -7,6 +7,7 @@ input_file: crates/oxc_isolated_declarations/tests/fixtures/infer-return-type.ts
declare function foo(): number;
declare function bar(): ((number) | (undefined));
declare function baz();
declare function qux(): string;
==================== Errors ====================
@ -17,5 +18,5 @@ declare function baz();
13 |
14 | function baz() {
: ^^^
15 | if (true) {
15 | if (a) {
`----