Skip to content

Filter possible contextual return types from unions for async functions and generators #51196

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
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
46 changes: 33 additions & 13 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29777,7 +29777,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// and that call signature is non-generic, return statements are contextually typed by the return type of the signature
const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl as FunctionExpression);
if (signature && !isResolvingReturnTypeOfSignature(signature)) {
return getReturnTypeOfSignature(signature);
const returnType = getReturnTypeOfSignature(signature);
const functionFlags = getFunctionFlags(functionDecl);
if (functionFlags & FunctionFlags.Generator) {
return filterType(returnType, t => {
return !!(t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void | TypeFlags.InstantiableNonPrimitive)) || checkGeneratorInstantiationAssignabilityToReturnType(t, functionFlags, /*errorNode*/ undefined);
});
}
if (functionFlags & FunctionFlags.Async) {
return filterType(returnType, t => {
return !!(t.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void | TypeFlags.InstantiableNonPrimitive)) || !!getAwaitedTypeOfPromise(t);
});
}
return returnType;
}
const iife = getImmediatelyInvokedFunctionExpression(functionDecl);
if (iife) {
Expand Down Expand Up @@ -38359,7 +38371,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// There is no point in doing an assignability check if the function
// has no explicit return type because the return type is directly computed
// from the yield expressions.
const returnType = getReturnTypeFromAnnotation(func);
let returnType = getReturnTypeFromAnnotation(func);
if (returnType && returnType.flags & TypeFlags.Union) {
returnType = filterType(returnType, t => checkGeneratorInstantiationAssignabilityToReturnType(t, functionFlags, /*errorNode*/ undefined));
}
const iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
const signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
const signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
Expand Down Expand Up @@ -39287,17 +39302,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
error(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation);
}
else {
// Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
// However, that would not catch the error in the following case.
//
// interface BadGenerator extends Iterable<number>, Iterator<string> { }
// function* g(): BadGenerator { } // Iterable and Iterator have different types!
//
const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(IterationTypeKind.Yield, returnType, (functionFlags & FunctionFlags.Async) !== 0) || anyType;
const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(IterationTypeKind.Return, returnType, (functionFlags & FunctionFlags.Async) !== 0) || generatorYieldType;
const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(IterationTypeKind.Next, returnType, (functionFlags & FunctionFlags.Async) !== 0) || unknownType;
const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & FunctionFlags.Async));
checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeErrorLocation);
checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags, returnTypeErrorLocation);
}
}
else if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) {
Expand All @@ -39310,6 +39315,21 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}

function checkGeneratorInstantiationAssignabilityToReturnType(returnType: Type, functionFlags: FunctionFlags, errorNode?: TypeNode) {
// Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
// However, that would not catch the error in the following case.
//
// interface BadGenerator extends Iterable<number>, Iterator<string> { }
// function* g(): BadGenerator { } // Iterable and Iterator have different types!
//
const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(IterationTypeKind.Yield, returnType, (functionFlags & FunctionFlags.Async) !== 0) || anyType;
const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(IterationTypeKind.Return, returnType, (functionFlags & FunctionFlags.Async) !== 0) || generatorYieldType;
const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(IterationTypeKind.Next, returnType, (functionFlags & FunctionFlags.Async) !== 0) || unknownType;
const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & FunctionFlags.Async));

return checkTypeAssignableTo(generatorInstantiation, returnType, errorNode);
}

function checkClassForDuplicateDeclarations(node: ClassLikeDeclaration) {
const instanceNames = new Map<__String, DeclarationMeaning>();
const staticNames = new Map<__String, DeclarationMeaning>();
Expand Down
4 changes: 2 additions & 2 deletions tests/baselines/reference/contextualTypeOnYield1.types
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ type FuncOrGeneratorFunc = () => (number | Generator<(arg: number) => void, any,

const f: FuncOrGeneratorFunc = function*() {
>f : FuncOrGeneratorFunc
>function*() { yield (num) => console.log(num); // `num` should be inferred to have type `number`.} : () => Generator<(num: number) => void, void, unknown>
>function*() { yield (num) => console.log(num); // `num` should be inferred to have type `number`.} : () => Generator<(num: number) => void, void, void>

yield (num) => console.log(num); // `num` should be inferred to have type `number`.
>yield (num) => console.log(num) : any
>yield (num) => console.log(num) : void
>(num) => console.log(num) : (num: number) => void
>num : number
>console.log(num) : void
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/contextualTypeOnYield2.types
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ type OrGen = () => (number | Generator<string, (arg: number) => void, undefined>

const g: OrGen = function* () {
>g : OrGen
>function* () { return (num) => console.log(num);} : () => Generator<never, (num: number) => void, unknown>
>function* () { return (num) => console.log(num);} : () => Generator<never, (num: number) => void, undefined>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All 3 affected baselines are directly related to the change and they are improvements/fixes


return (num) => console.log(num);
>(num) => console.log(num) : (num: number) => void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,182 @@ async function fn4(): Promise<Obj> {

});
}

declare class Context {
>Context : Symbol(Context, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 20, 1))

private _runnable;
>_runnable : Symbol(Context._runnable, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 22, 23))
}
type Done = (err?: any) => void;
>Done : Symbol(Done, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 24, 1))
>err : Symbol(err, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 25, 13))

type Func = (this: Context, done: Done) => void;
>Func : Symbol(Func, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 25, 32))
>this : Symbol(this, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 26, 13))
>Context : Symbol(Context, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 20, 1))
>done : Symbol(done, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 26, 27))
>Done : Symbol(Done, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 24, 1))

type AsyncFunc = (this: Context) => PromiseLike<any>;
>AsyncFunc : Symbol(AsyncFunc, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 26, 48))
>this : Symbol(this, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 27, 18))
>Context : Symbol(Context, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 20, 1))
>PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --))

interface TestFunction {
>TestFunction : Symbol(TestFunction, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 27, 53))

(fn: Func): void;
>fn : Symbol(fn, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 30, 3))
>Func : Symbol(Func, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 25, 32))

(fn: AsyncFunc): void;
>fn : Symbol(fn, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 31, 3))
>AsyncFunc : Symbol(AsyncFunc, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 26, 48))

(title: string, fn?: Func): void;
>title : Symbol(title, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 32, 3))
>fn : Symbol(fn, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 32, 17))
>Func : Symbol(Func, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 25, 32))

(title: string, fn?: AsyncFunc): void;
>title : Symbol(title, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 33, 3))
>fn : Symbol(fn, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 33, 17))
>AsyncFunc : Symbol(AsyncFunc, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 26, 48))
}

declare const test: TestFunction;
>test : Symbol(test, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 36, 13))
>TestFunction : Symbol(TestFunction, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 27, 53))

interface ProcessTreeNode {
>ProcessTreeNode : Symbol(ProcessTreeNode, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 36, 33))

pid: number;
>pid : Symbol(ProcessTreeNode.pid, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 38, 27))

name: string;
>name : Symbol(ProcessTreeNode.name, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 39, 14))

memory?: number;
>memory : Symbol(ProcessTreeNode.memory, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 40, 15))

commandLine?: string;
>commandLine : Symbol(ProcessTreeNode.commandLine, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 41, 18))

children: ProcessTreeNode[];
>children : Symbol(ProcessTreeNode.children, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 42, 23))
>ProcessTreeNode : Symbol(ProcessTreeNode, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 36, 33))
}

export declare function getProcessTree(
>getProcessTree : Symbol(getProcessTree, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 44, 1))

rootPid: number,
>rootPid : Symbol(rootPid, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 46, 39))

callback: (tree: ProcessTreeNode) => void
>callback : Symbol(callback, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 47, 18))
>tree : Symbol(tree, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 48, 13))
>ProcessTreeNode : Symbol(ProcessTreeNode, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 36, 33))

): void;

test("windows-process-tree", async () => {
>test : Symbol(test, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 36, 13))

return new Promise((resolve, reject) => {
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --))
>resolve : Symbol(resolve, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 52, 22))
>reject : Symbol(reject, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 52, 30))

getProcessTree(123, (tree) => {
>getProcessTree : Symbol(getProcessTree, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 44, 1))
>tree : Symbol(tree, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 53, 25))

if (tree) {
>tree : Symbol(tree, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 53, 25))

resolve();
>resolve : Symbol(resolve, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 52, 22))

} else {
reject(new Error("windows-process-tree"));
>reject : Symbol(reject, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 52, 30))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
}
});
});
});

interface ILocalExtension {
>ILocalExtension : Symbol(ILocalExtension, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 61, 3))

isApplicationScoped: boolean;
>isApplicationScoped : Symbol(ILocalExtension.isApplicationScoped, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 63, 27))

publisherId: string | null;
>publisherId : Symbol(ILocalExtension.publisherId, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 64, 31))
}
type Metadata = {
>Metadata : Symbol(Metadata, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 66, 1))

updated: boolean;
>updated : Symbol(updated, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 67, 17))

};
declare function scanMetadata(
>scanMetadata : Symbol(scanMetadata, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 69, 2))

local: ILocalExtension
>local : Symbol(local, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 70, 30))
>ILocalExtension : Symbol(ILocalExtension, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 61, 3))

): Promise<Metadata | undefined>;
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --))
>Metadata : Symbol(Metadata, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 66, 1))

async function copyExtensions(
>copyExtensions : Symbol(copyExtensions, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 72, 33))

fromExtensions: ILocalExtension[]
>fromExtensions : Symbol(fromExtensions, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 74, 30))
>ILocalExtension : Symbol(ILocalExtension, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 61, 3))

): Promise<void> {
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --))

const extensions: [ILocalExtension, Metadata | undefined][] =
>extensions : Symbol(extensions, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 77, 7))
>ILocalExtension : Symbol(ILocalExtension, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 61, 3))
>Metadata : Symbol(Metadata, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 66, 1))

await Promise.all(
>Promise.all : Symbol(PromiseConstructor.all, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --))
>all : Symbol(PromiseConstructor.all, Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --))

fromExtensions
>fromExtensions .filter((e) => !e.isApplicationScoped) .map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --))
>fromExtensions .filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>fromExtensions : Symbol(fromExtensions, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 74, 30))

.filter((e) => !e.isApplicationScoped)
>filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>e : Symbol(e, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 80, 17))
>e.isApplicationScoped : Symbol(ILocalExtension.isApplicationScoped, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 63, 27))
>e : Symbol(e, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 80, 17))
>isApplicationScoped : Symbol(ILocalExtension.isApplicationScoped, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 63, 27))

.map(async (e) => [e, await scanMetadata(e)])
>map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --))
>e : Symbol(e, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 81, 20))
>e : Symbol(e, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 81, 20))
>scanMetadata : Symbol(scanMetadata, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 69, 2))
>e : Symbol(e, Decl(contextuallyTypeAsyncFunctionReturnType.ts, 81, 20))

);
}

Loading