Hacker News new | ask | show | jobs
by mrblampo 1200 days ago
Interesting! The example

[1, 2, undefined].filter(Boolean). // number[]

is interesting because it makes use of the fact that the types of individual array members are known at compile time. I can think of some times when I have dealt with arrays that are defined at compile time, but not where I've needed to call .filter on such an array. Is there a common use case here?

2 comments

I think that's just a contrived example. It looks like it should work with types like `(string | null)[]`, where individual members are only known on runtime.

That's very appealing to be; I commonly .map() an array to a nullable type, then want to filter out the nulls.

How could it help with anything at runtime? The type system only exists at compile time, right?
Yeah, it only exists at compile time, so in "real" code you won't know the type of e.g., array index 2 at compile-time, but you will know "each item in this array is either type A or type B".

You'll often want to work on only the A's in the array, and so you need to whittle down the data, but also inform TypeScript that you've done so. The return type on your .filter() callback tell TS what type the entire resulting array should be.

When filtering out nulls, you normally have to write a user-defined type guard everywhere you call .filter(), which is irksome, so this project configures the built-in Boolean() function to behave similarly when passed to .filter().

Reading https://github.com/total-typescript/ts-reset/blob/main/src/e..., I'm more confused than before. The generic NonFalsy<T>[] looks to me like it should evaluate to never[] if the entire array is false, and to T[] (the original array type, not narrowed) otherwise. But I can see that the test case demonstrates that it works. What am I missing?