#Inferred type predicate in filter function not getting inferred

10 messages · Page 1 of 1 (latest)

smoky scaffold
#

Hey all, just trying to figure out why this filter function isn't getting its type predicate inferred. I've set up a simple example on the playground

daring yachtBOT
#
advdanny#0

Preview:```ts
let arrMaybePromise: (string | Promise<string>)[] = []

// works
const arrPromises = arrMaybePromise.filter(
e => e instanceof Promise
)

// doesn't work
const arrNotPromises = arrMaybePromise.filter(
e => !(e instanceof Promise)
)
...```

crisp oasis
#

for !(e instanceof Promise) to work as a general typeguard, ts would need to have negated types (to say, "not Promise") which ts currently doesn't have

#

or be generic and Exclude Promise from the input type, which wouldn't be inferred afaik

#

(something like this)

daring yachtBOT
#
that_guy977#0

Preview:ts ... function notPromise<T>(x: T): x is Exclude<T, Promise<unknown>> { return !(x instanceof Promise) } const arrNotPromises_ = arrMaybePromise.filter(notPromise) // ^? ...

smoky scaffold
#

Oh so conceptually because I can't do is (not Promise) in a type predicate, then there's no type predicate that can be inferred from e => !(e instanceof Promise)

crisp oasis
#

right

smoky scaffold
#

Thanks, that makes sense. I was getting narrowing mixed up with type predicates it seems

#

Thanks @crisp oasis