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)
-
-
Since it's a bool, not a type guard, `isB &&` doesn't have the effect of changing the type of `aOrB`. As far as I can tell there's no way to assign a type guard to a variable.
-
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.
- 1 more reply
New conversation -
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.