develwoutacause’s avatardevelwoutacause’s Twitter Archive—№ 990

  1. I just learned that #TypeScript can actually type narrow Array.prototype.filter via an is clause: const values = ['a', 'b', null, 'd']; const result = values.filter((v): v is string => !!v); // Inferred as string[]! typescriptlang.org/play?#code/MYewdgzgLgBAbgQwDYFcCmEYF4YG0DkC+ANDPgEYkxgpJKn4Am+AugNwBQoksAThrVg5EqDADoAZgEskUNLwAUCuAEoAXPBhTM0XlLABzbAD4YAQjOq2QA
    1. …in reply to @develwoutacause
      What's extra cool is that this is *not* special-cased in the compiler. Apparently you can use is in a type declaration to declare a new generic as part of the expression, here is the source for Array.prototype.filter: github.com/microsoft/TypeScript/blob/404a7d602df9c19d98d49e6a6bf2295e423be676/lib/lib.es5.d.ts#L1176
      1. …in reply to @develwoutacause
        1. …in reply to @develwoutacause
          Now if only we could somehow make: (value: T) => !!value infer to (value: T): value is NonNullable<T> => !!value we'd be golden. Is there any reason the compiler can't do that? It already type narrows, we'd just need to plumb it through to the return type.
          1. …in reply to @develwoutacause
            I guess the tricky part here is probably remembering that it came from a function parameter and tying the return type to the narrowed form of that parameter. It also assumes that value is not modified, which may not always be true, but would probably break inference anyways.