Reputation: 15317
I have a function with a union type between string
and a function type. How can I write a type guard to narrow to that function type? (The following doesn't work.)
interface Callback {
(args: any[]): void
}
var fn = function(arg: string | Callback) {
if (typeof arg == 'Callback') {
arg.call([]);
}
}
Upvotes: 1
Views: 1716
Reputation: 106640
typeof
won't ever return 'Callback'
. In this scenario it will work to do an instanceof Function
check:
interface Callback {
(args: any[]): void
}
var fn = function(arg: string | Callback) {
if (arg instanceof Function) {
arg.call([]);
}
};
Alternatively this also works:
if (typeof arg === "function") {
arg.call([]);
}
Upvotes: 5