Discriminated Unions with Boolean Discriminators
The key takeaway from this exercise is understanding that the discriminator in a discriminated union doesn't have to be a string.
In this case, we'll use a boolean. This will be highly handy in instances where we want to discriminate based on the success or failure of an operation.
To determine h
Transcript
00:00 Okay, the key idea from this exercise is that discriminated unions the discriminator doesn't have to be a string. It can be a boolean and Here we can do basically we can turn this to Succeeded true and if it's true, then we will pass the users back or we will use false
00:18 And then in that case pass back a string and so inside the responses that we're returning here You can see we're returning false and then an error occurred if we were to change this to be true Then type string is not assignable to type user beautiful. And now the same behavior is true down at the bottom
00:34 We've got succeeded which is true or false which typescript just elides to be boolean Very clever, then we've got value here, which could be string or user and we're doing the same checks We're checking if succeeded was true. And if it was true, then it's a value as a user Otherwise value is a string so this works in discriminated tuples
00:54 It also works in discriminated unions of objects too. You can have like it doesn't have to be just literal strings in there You can have numbers in there You can have booleans as they are here and this works in the same narrowing sense as D structure tuples super cool