#Help with asserting value is not undefined.
26 messages · Page 1 of 1 (latest)
You can either check the actual value in the check, or you put the check into a function, which sometimes will do what you want
TS doesn't 'remember' what narrowing a certain boolean implies - instead of using booleans it can be useful to use NarrowedValue | undefined
In this case that would look like:
const nonNullRange =
range && range.from && range.to
? { from: range.from, to: range.to }
: undefined;
if (nonNullRange) {
return formatISO(nonNullRange.from) + " - " + formatISO(nonNullRange.to);
}
TS Playground is having real trouble with the types in that playground for me. Any better for you Retsam?
oh now it's alive
Yeah, kinda looks like react-day-picker is spawning a bunch of errors that is messing up the ability to resolve types
Preview:```ts
import {DateRange} from "react-day-picker"
import {formatISO} from "date-fns"
import {useState} from "react"
type ValidDateRange = {
from: Date
to: Date
}
function hasSelectedRange(
range: DateRange | undefined
): range is ValidDateRange {
return (
range !== undefined &&
range.from !== undefined &&
range.to !== undefined
)
...```
it started working for some reason
Anyway here is a solution using a type guarding function
Sometimes TS will infer the return assertions for this automatically, I seemed to need to do it manually here
It only infers retun types for type-guards when you pass a callback to something typed as accepting a type-guard
Probably, yeah.
maybe we should have a(): infer predicate option
Yeah, I've considered that, though I think the inferring callbacks covers like 90% of the cases anyway.
Hmm I use this type of type guard a lot. Rarely use .filter etc
I wouldn't use one here and wouldn't recommend it
It's not typesafe or honestly that convenient.
I guess the reason for this code is to avoid rechecking. So for that you'd need something like your suggestion
Yeah, my preference order here is probably:
- Just inline the check (can drop
!== undefinedto make it less verbose) - Use the
NarrowedValue | undefinedpattern (useful if it's repeated) - 🤷♂️ just
!and it's pretty clear why it's okay to assert in context.
I used type guards a lot when making my JSX framework and needing to be able to narrow down Nodes to the specific type often
A Node being a primitive or object, or array, and the object could be an HTML el, a function component or a class components. So the checks to identify which get a bit onerous.
Would be nice if the assertion was typesafe though. I wonder if there is any value in comparing the inferred predicate to the stated predicate. But should pretty stop OTing the thread now