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 guard from Function | RegExp to Function fails #4850

Closed
dsherret opened this issue Sep 18, 2015 · 2 comments
Closed

Type guard from Function | RegExp to Function fails #4850

dsherret opened this issue Sep 18, 2015 · 2 comments
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead

Comments

@dsherret
Copy link
Contributor

Is this a bug?

var a: Function | RegExp;

if (typeof a === "function") {
    a(100); // compile error, still a Function | RegExp
}

...since the typeof a RegExp will be an object and RegExp is a type that lacks a call signature.

It works fine when a user-defined type guard is used, which seems inconsistent:

function isFunction(obj: any) : obj is Function {
    return typeof obj === "function";
}

var a: Function | RegExp;

if (isFunction(a)) {
    a(10); // no compile error
}

Version: TypeScript 1.6
Discovered here.

@dsherret dsherret changed the title Type guard from RegEx | Function to Function fails Type guard from Function | RegExp to Function fails Sep 18, 2015
@danquirk
Copy link
Member

Today the === pattern for type guards only supports the literal types. The supported pattern for type guarding function types is to use instanceof. So this does work:

var a: Function | RegExp;

if (a instanceof Function) {
    a(100); // ok
}

This is usually the general recommendation for doing actual type tests on functions in JavaScript anyway.

@danquirk danquirk added the By Design Deprecated - use "Working as Intended" or "Design Limitation" instead label Sep 18, 2015
@RyanCavanaugh
Copy link
Member

Logged #4868

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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