Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
22 changes: 8 additions & 14 deletions src/services/codefixes/fixReturnTypeInAsyncFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,20 @@ namespace ts.codefix {
});

function getInfo(sourceFile: SourceFile, checker: TypeChecker, pos: number): Info | undefined {
const returnTypeNode = getReturnTypeNode(sourceFile, pos);
if (isInJSFile(sourceFile)) {
return undefined;
}

const token = getTokenAtPosition(sourceFile, pos);
const func = findAncestor(token, isFunctionLikeDeclaration);
const returnTypeNode = func?.type;
if (!returnTypeNode) {
return undefined;
}

const returnType = checker.getTypeFromTypeNode(returnTypeNode);
const promisedType = checker.getAwaitedType(returnType) || checker.getVoidType();
const promisedTypeNode = checker.typeToTypeNode(promisedType);
const promisedTypeNode = checker.typeToTypeNode(promisedType, /*enclosingDeclaration*/ returnTypeNode, /*flags*/ undefined);
if (promisedTypeNode) {
return { returnTypeNode, returnType, promisedTypeNode, promisedType };
}
Expand All @@ -55,16 +61,4 @@ namespace ts.codefix {
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, returnTypeNode: TypeNode, promisedTypeNode: TypeNode): void {
changes.replaceNode(sourceFile, returnTypeNode, createTypeReferenceNode("Promise", [promisedTypeNode]));
}

function getReturnTypeNode(sourceFile: SourceFile, pos: number): TypeNode | undefined {
if (isInJSFile(sourceFile)) {
return undefined;
}

const token = getTokenAtPosition(sourceFile, pos);
const parent = findAncestor(token, isFunctionLikeDeclaration);
if (parent?.type) {
return parent.type;
}
}
}
20 changes: 20 additions & 0 deletions tests/cases/fourslash/codeFixReturnTypeInAsyncFunction18.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/// <reference path='fourslash.ts' />

// @target: es2015
////
////interface A {}
////export { A as PublicA };
////async function foo(): A {
//// return {}
////}

verify.codeFix({
index: 0,
description: [ts.Diagnostics.Replace_0_with_Promise_1.message, "A", "A"],
newFileContent: `
interface A {}
export { A as PublicA };
async function foo(): Promise<A> {
return {}
}`
});