#type narrow using instanceof

16 messages · Page 1 of 1 (latest)

foggy atlas
#

Hello, trying to type narrow using an instanceof check in a helper that returns a boolean. I would expect that if I use an if statement with the helper, the next line would type narrow. However it doesn't.

However, while type narrowing works without a helper function. With a helper function it doesn't seem to work. See sample below

class testing {};

// this code doesn't work
const check = (arg1: any) => {
    return arg1 instanceof testing
}
const doesTypeWork = (arg1: any) => {
    if (check(arg1)) {
        const me = arg1; // still shows as any ????
    }
}

// this code does work

const checkThatWorks = (arg1: any) => {
    if (arg1 instanceof testing) {
        const something = arg1 // the type narrowing is successful! TypeScript sees this as 
    }
}
hollow grotto
#

You need to make your function a type guard:

const check = (arg1: any): arg1 is testing => {
    return arg1 instanceof testing
}
#

It's not practical for TS to scan every single function call and look into the source code to figure out if something is a type guard.

foggy atlas
#

That solution was very helpful.

Don't particular understand why it's not practical. I don't particularly see it as any different than TS inferring any other return type.

prime finch
#

return types are really easily statically analyzable, just check what values are returned from each return statement
predicates on the other hand, the value being returned doesn't have any correlation to "x is string" or whatever

#

consider this:

function fn(x) {
  const t = typeof x;
  const s = t[1] === "t";
  return s;
}
```this is technically a valid and statically checkable way to check for `x is string`
noone in their right mind is going to do this, but it's valid, and reasonable versions of this do exist and are used
it's hard for even a human to see what's going on here, typescript can't possibly go through the entire function and determine what the return type *means*

to get consistent results, you'd have to just run the function in some capacity, which isn't feasible for static analysis, and also requires you to be able to solve the halting problem, which we're quite a ways off from
#

there's also intent; was the given function meant to be a typeguard in the first place?

frank zephyr
prime finch
#

because "when directly used" is a very faint line

#

automatic typeguard inference probably wouldn't result in errors, but it'd definitely result in some bad UX for false positives

frank zephyr
prime finch
#

that's just narrowing for scopes though, that won't work for type guard behavior

sinful sunBOT
worldly trench
#

!ts