#Is it possible to narrow a union type in a shorter way than "x" in obj, like with obj?.x ?

1 messages · Page 1 of 1 (latest)

rare steppe
#

It is a common problem to have a union of types and to narrow the union by looking into a property that isn't on all members of the union, but this causes a TS error. Is there a way to do the narrowing that doesn't require always checking if the property is "in" the object, since that already happens with the optional chaining obj?.prop ?

proud meteorBOT
#
bendman#2685

Preview:```ts
...
if (root?.type === "p") {
// Error
// root should be P
}

if ("type" in root && root.type === "p") {
// root is P
}```

brazen raft
#

I don't think there is any simple way to do this, no.

#

You could theoretically write some sort of helper function for it:

proud meteorBOT
#

declare function matches<T, const U>(t: T, u: U): t is Extract<T, U>;
if(matches(root, { type: "p"})) {
  root
// ^? - const root: P
}