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

Type narrowing for generic types #1726

Closed
laszlojakab opened this issue Jan 19, 2015 · 1 comment
Closed

Type narrowing for generic types #1726

laszlojakab opened this issue Jan 19, 2015 · 1 comment
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead

Comments

@laszlojakab
Copy link

Hi,

Type narrowing not working in the following situation (maybe caused by generic type?):

interface Options<T> {
    opt: T|(() => T);
}

function MyFunc<T>(options: Options<T>) {
    var opt = options.opt;
    if (typeof opt === "function")
    {
        var k = opt; // k is "T | (() => T)" but should be "() => T"
    }
}

///////////////////////////////////

var options: Options<number>;
var opt = options.opt;

if (typeof opt === "function")
{
    var k = opt; // k is "() => number", it is OK
}
@ahejlsberg
Copy link
Member

This is by design. In the type T | (() => T), T itself could be a function type so we can't conclude anything from the typeof test.

However, when the type is number | () => number we can indeed tell the difference.

@ahejlsberg ahejlsberg added the By Design Deprecated - use "Working as Intended" or "Design Limitation" instead label Jan 19, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead
Projects
None yet
Development

No branches or pull requests

3 participants