Issue
const isNonNullable = <V>(value: V): value is NonNullable<V> =>
value !== null && value !== undefined
How to make a generic type guard function like this one, but for the ([key, value]) entry?
I want to use it like this: Object.entries(foobar).filter(isNonNullableEntry).
const isNonNullableEntry = <T extends [K, V]>(entry: T): entry is [K, NonNullable<V>] =>
entry[1] !== null && entry[1] !== undefined
The above is my incorrect attempt. How to make it right?
Solution
"A type guard is some expression that performs a runtime check that guarantees the type in some scope." docs
The isNonNullableEntry typeguard is parametrized by two arbitrary types K and V. The argument is a [K, V] tuple, so we use the typeguard to tell the compiler that it is guaranteed to be a [K, NonNullable<V>], which is a subset of the [K, V], so a valid case for using a typeguard.
const isNonNullableEntry = <K,V>(entry: [K, V]): entry is [K, NonNullable<V>] =>
entry[1] !== null && entry[1] !== undefined
Answered By - D Pro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.