ckknight/gorillascript

Typecheck operator

ckknight opened this issue · 5 comments

It could be handy to be able to typecheck an expression, not just when used as a function param.

There would be two ways to do this, one that would error on mismatch and one that would fall back to a specified default:

let x = (unknown() as Number) // could throw a TypeError if result isn't a Number. Would be a no-op if DISABLE_TYPE_CHECKING is true.
let y = (unknown() as Number = 0) // if result isn't a Number, evaluates `0`. Does not turn into a no-op if DISABLE_TYPE_CHECKING is true, as it introduces extra logic.

I'm not sure about the default value syntax and whether it should run in the case of any non-Number or just in the case of null or void (as is the case in function parameters now).

Random guy browsing through issues here...

why not use x = (unknown() is Number). its the same letters but would make things bit more readable.

= 0 would be hard to comprehend hence easy to exploit the wrong way. May be use a keyword or add

I can see use for y = (unknown() as Number).value() getting rid of those checks. in fact how about using y = (unknown() as Number).value(0) if unknown return a number and value() is used , we return the value of the number however if value(0) is used, we return 0. val() would be a feasible option as well. Any takers ?

as is used in other places where types are involved.

is is an operator borrowed from ECMAScript 6 to be an alias for Object.is(,)

I see absolutely no need to introduce the overhead of an object with a method called value. I don't see what it would add at all compared to having it run a simple check.

Should have made it clearer. The normal workflow would be condition check, if true do X else do Y type checks by itself don't really provide any value, its usually useful once you take the boolean outcome and make something from it.

I guess my intentions are a bit bigger than just type checks (since this would be much more useful for all types of conditions) . Usually I've noticed undefined being used as follows :

if variable is undefined 
    return default value 
else
    return variable value

I do agree that simple null would be useful (read: very very useful) but my question is would implementing something like value would be worth the overhead. Guessing currently that's a no.

Well, in your example with checking against undefined, one can this now: value ? other, which evaluates to value unless it is null or void, at which point it would execute other.

This would work similarly where value as T would either throw a TypeError or simply evaluate to value, at which point the static type analyzer would know that is a T.

When providing a default value, it would simply evaluate to that default value instead of throwing a TypeError.

Makes sense.