iTranslated by AI
Using typesafe-utils for Type-Safe Array filter()
Consider a case where you use the array filter method in TypeScript.
// items is (string|number)[]
const items = [1, 2, "foo", "baz"]
const stringItems: string[] = items.filter(item => typeof item === "string")
While we might expect stringItems to become string[], it remains (string|number)[].
To solve this, you need to use a Type Guard.
const items = [1, 2, "foo", "baz"]
const isString = (item): item is string => {
return typeof item === "string"
}
const stringItems: string[] = items.filter(isString)
Or like this:
const stringItems = items.filter((item): item is string => {
return typeof item === "string"
})
On the other hand, another approach would be to simply use as or @ts-ignore.
// @ts-ignore
const stringItems: string[] = items.filter(item => typeof item === "string")
const stringItems: string[] = items.filter(item => typeof item === "string") as string[]
Challenges
Since a Type Guard is just a declaration, it can return incorrect information.
const items = [1, 2, "foo", "baz"]
const isString = (item): item is string => {
// Even if it ends up like this due to some unfortunate modification, TypeScript will not detect it.
return typeof item === "string" || item === "number"
}
const stringItems: string[] = items.filter(isString)
To avoid this, the only way is to thoroughly test the Type Guard function.
Actually, considering that most cases for using filter are just for things like excluding null, it often feels like it's not worth the effort and is quite tedious.
Solution
In such cases, typesafe-util can be a handy alternative.
Although it's a library with not many stars at the moment, it provides a full set of utilities like isString, isTrue, isTruthy, and isNumber, which are well-typed and thoroughly tested.
For example, here is how you would use the isString we implemented earlier.
import { isString } from 'typesafe-utils'
const items = [1, 2, "foo", "baz"]
const stringItems = items.filter(isString)
Of course, if you need to do something very complex, you'll have to implement it yourself, but for simple tasks like null-checking, it should provide plenty of value.
Discussion