I was studying better type predicates and how they actually narrow the type through pet is Fish
, for example.
I've tried to create a simple Typescript playground
In doSomething
I use isFish
function.
isFish
is represented to have a return type pet is Fish
, but if I use it and assign the result to a variable, the result is kinda "casted" to a boolean
. So I guess pet is Fish
can be seen as a type itself.
So my question is: can pet is Fish
(or whatever similar expression) be considered a subtype of boolean, just like "Hello world"
is a subtype of string
?
type X = "hello world" | string;
// ^? type X = string
type Y = "hello world" & string;
// ^? type Y = "hello world"
Thank you!
CodePudding user response:
No this is not really equivalent to const strings. Booleans have only two possible values, i.e. boolean
is the same as true | false
, you cannot narrow that type other than having just true
or false
.
I would think of type guard as being a special syntax, a function like isFish(pet: Cat | Dog | Fish): pet is Fish
returns a boolean, and the compiler knows if that boolean is true
that the pet
variable is in fact a Fish
, or if false
then it is not a Fish
, and narrows the type of the pet
variable e.g.:
const pet: Cat | Dog | Fish = getPet();
if (isFish(pet) {
// pet now has type Fish
} else {
// pet now has type Cat | Dog
}