TypeScript: type A = {kind: "a"} type B = {kind: "b"} type AorB = A | B function takesB(b: B) { } function makeB(): AorB { return {kind: "b"} } I can do: const b = makeB() b.kind === "b" && takesB(b) But how do I make this work? const isB = b.kind === "b" isB && takesB(b)
-
-
I think the key is that the type of `b` is `B | undefined`, which is a simple type that doesn't depend on any of this type guarding business. So when the compiler sees `b && ...`, it doesn't know or care *why* `b` may be undefined.
-
You mean the type of `definitelyB`, right? It’s false | B, but same effect as if it were undefined | B
End of conversation
New conversation -
-
-
I wonder how f there's some way to preserve the type guard return type? I tried to use identity function <T>(a: T): T => a or ReturnType<typeof Guard> , to no avail
-
Opening an issue?
- 1 more reply
New conversation -
-
-
ohhhhhh.... I understand. I was confused why you put what looked like an existence check after checking aOrB.thing - very nicely done
Thanks. Twitter will use this to make your timeline better. UndoUndo
-
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.