Skip to content

Generic functions that have a function as a parameter expand inferred type instead of narrowing #26127

Closed
@nomcopter

Description

@nomcopter

TypeScript Version: typescript@3.1.0-dev.20180801

Search Terms: Generic Type Inference Function Parameter Union

Code

interface Foo {
    foo: number;
}

declare function acceptUnion(foo: Foo | number): void;
declare var foo: Foo;

declare function erroneouslyExpands<T>(value: T, func: (t: T) => void): T;

 // Errors, TS infers the result as `Foo | number`
const test: Foo = erroneouslyExpands(foo, acceptUnion);

Note: This case is common when passing comparators into functions.

Expected behavior:

T should be inferred as Foo.

Actual behavior:

T is expanded based on what func accepts.

Playground Link: https://www.typescriptlang.org/play/index.html#src=interface%20Foo%20%7B%0A%20%20%20%20foo%3A%20number%3B%0A%7D%0A%0Adeclare%20function%20acceptUnion(foo%3A%20Foo%20%7C%20number)%3A%20void%3B%0Adeclare%20var%20foo%3A%20Foo%3B%0A%0Adeclare%20function%20erroneouslyExpands%3CT%3E(value%3A%20T%2C%20func%3A%20(t%3A%20T)%20%3D%3E%20void)%3A%20T%3B%0A%0Aconst%20test%3A%20Foo%20%3D%20erroneouslyExpands(foo%2C%20acceptUnion)%3B%0A

Related Issues:

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions