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 @garybernhardt
is there a reason this works but it doesn't work if you try to put the conditionals inline?
1 reply 0 retweets 0 likes -
Replying to @JoshMarantz @garybernhardt
(Not an expert in TS, this is just my understanding. Take it with a grain of salt). `const b = aOrB.kind ==="b" && b` assigns a new variable with a known type of `B`. `const isB = b.kind === "b"` assigns a variable of type `boolean` not `b is B`.
1 reply 0 retweets 1 like -
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.
3 replies 0 retweets 2 likes -
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
2 replies 0 retweets 0 likes
Opening an issue?
-
-
I will when I'll get back to keyboard
0 replies 0 retweets 0 likesThanks. 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.