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)
-
Show this thread
-
This is super genericized to fit in a tweet, but this exact situation comes up all the time in my React components.
4 replies 0 retweets 1 likeShow this thread -
Replying to @garybernhardt
Does this fit your needs? function isB(aOrB: AorB): aOrB is B { return aOrB.kind === "b" } isB(b) && takesB(b);
1 reply 0 retweets 0 likes -
Replying to @sgrif
It will help. My goal here is to avoid breaking JSX lines. I have: {chooseable.kind === "lesson"&& ... You propose this, which is shorter: isLesson(chooseable) && ... But what I really want is: isLesson && ...
1 reply 0 retweets 0 likes -
Replying to @garybernhardt
Yeah, I don't think it's possible to get exactly that (since once it's assigned it's a bool and no longer a type guard). This is one other option though? const definitelyB = b.kind === "b" && b; definitelyB && takesB(definitelyB);
2 replies 0 retweets 8 likes -
Replying to @sgrif
It is! And it says exactly what it means without any fancy language features! Thank you!
2 replies 0 retweets 5 likes
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.