Say I have the following code:
var x interface{}
y := 4
x = y
fmt.Println(reflect.TypeOf(x))
This will print int as the type. My question is how can I test for the type? I know there is the type switch which does this, so I could do:
switch x.(type) {
case int:
fmt.Println("This is an int")
}
But if I only want to check for just one specific type the switch seems like the wrong tool. Is there a more direct method of doing this like
reflect.TypeOf(x) == int
or is the type switch the way to go?
Use the strict equality operator (===) to check if two strings are equal in TypeScript, e.g. if (str1 === str2) {} . The strict equality operator returns true if the strings are equal, otherwise false is returned.
To check if two slices are equal, write a custom function that compares their lengths and corresponding elements in a loop. You can also use the reflect. DeepEqual() function that compares two values recursively, which means it traverses and checks the equality of the corresponding data values at each level.
In Typescript, we have three ways to work with it using: typeof: the keyword helps to check values types, like boolean, string, number, etc. instanceof: the keyword to compare the object instance with a class constructor. type guards: The powerful way to check types using typescript feature language.
Type assertions return two values .. the first is the converted value, the second is a bool indicating if the type assertion worked properly.
So you could do this:
_, ok := x.(int)
if ok {
fmt.Println("Its an int")
} else {
fmt.Println("Its NOT an int")
}
..or, shorthand:
if _, ok := x.(int); ok {
fmt.Println("Its an int")
}
See it in the playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With