Skip to content
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

Generic return type of generic function gets not resolved correctly with *typeof* #17859

Closed
lochbrunner opened this issue Aug 17, 2017 · 3 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@lochbrunner
Copy link

TypeScript Version: 2.4.2

Code

function foo<T>(input: T): T {
    if (typeof input === 'number') {
        return 10;
    }
    if (typeof input === 'string') {
        return 'Hallo';
    }
    return input;
}

Expected behavior:

No compiler error.

Actual behavior:

Type '10' is not assignable to type 'T'.
Type '"Hallo"' is not assignable to type 'T'.

@aluanhaddad
Copy link
Contributor

10 is assignable to type number.
When the first if condition is met, we know that, whatever T is, it is also assignable to type number.
This does not imply that 10 is assignable to T.

@mhegazy mhegazy added Suggestion An idea for TypeScript In Discussion Not yet reached consensus Design Limitation Constraints of the existing architecture prevent this from being fixed and removed In Discussion Not yet reached consensus Suggestion An idea for TypeScript labels Aug 29, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Aug 29, 2017

Narrowing currently works on a single variable, i.e. type of input inside these blocks would be number & T or string & T, but it does not narrow related types, i.e. T itself to a number or string. doing such non-local narrowing is fairly expensive.

@mhegazy
Copy link
Contributor

mhegazy commented Sep 12, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

3 participants