Welcome to the Onshape forum! Ask questions and join in the discussions about everything Onshape.
First time visiting? Here are some places to start:- Looking for a certain topic? Check out the categories filter or use Search (upper right).
- Need support? Ask a question to our Community Support category.
- Please submit support tickets for bugs but you can request improvements in the Product Feedback category.
- Be respectful, on topic and if you see a problem, Flag it.
If you would like to contact our Community Manager personally, feel free to send a private message or an email.
Is there a built-in way to test if a variable is of a specific type?
blackslate
Member Posts: 16 ✭
The documentation indicates that there are 9 standard types:
However, I have found no standard method to check if a given variable is of a given type. Have I not been looking hard enough?
I have found a workaround, by creating a `testType` function and overloading it for each type, so that the different overloaded versions return the name of the type that they receive as an argument.
You can find my proof of concept here.
- Boolean
- Number
- String
- Array
- Map
- Box
- Function
- Builtin
- Undefined
I have found a workaround, by creating a `testType` function and overloading it for each type, so that the different overloaded versions return the name of the type that they receive as an argument.
function testType(value is array) {<br> return "array";<br>}<br><br>function testType(value is boolean) {<br> return "boolean";<br><div>}</div><div><br></div><div>// ... and so on<br><br>function isArray (value) {<br> return (testType(value) == "array");<br>}<br></div>(The Format > Code option makes the code above look terrible in Preview. Let's hope it appears correctly in the forum.)
You can find my proof of concept here.
Is my workaround really necessary, or is there a built-in method that I have overlooked?
0
Best Answers
-
ilya_baran Onshape Employees, Developers, HDM Posts: 1,215You can use the "is" operator, as in:
if (myVariable is array) { // Handle array case }
Ilya Baran \ VP, Architecture and FeatureScript \ Onshape Inc1
Answers
Where is the "is" operator documented?
https://cad.onshape.com/FsDoc/type-tags.html