2 ms·
> ... I've never once changed the type of a variable. I only do that for functions that accept multiple types (accept liberally and all that), but internally c
by yorwba 9y ago
> ... I've never once changed the type of a variable.
I only do that for functions that accept multiple types (accept liberally and all that), but internally convert them into a canonical representation. For example, if a plain string is to be treated the same as an object with a name property, I will have code like
if(typeof(x) === "string") {
x = {name: x}
}
I like how Rust just lets you declare a new variable with the same name but different type, which then shadows the previous declaration for the rest of the scope.
- pier25 9y agoIn those cases I usually create a new function depending on the type. So for example I have a "main" function that does something with a date and expects a date object: doSomething(date) And then if I want to pass a string I do something like: doSomethingString(date) { doSomething(new Date(date)) }