Preparing for type guards

# Axel Rauschmayer (13 years ago)

Once we have type guards, I would expect the JavaScript programming style to slightly change. Currently, number-valued arguments are implemented like this:

function foo(x) {
    x = Number(x);
}

With guards, you would use:

function foo(x :: Number) {
}

It might make sense to standardize simple guard methods now, for example:

function foo(x) {
    Object.guard(x, Number);
}

Advantages: Helps tools (to infer types, to generate documentation), can later be refactored to real guards.

# Brendan Eich (13 years ago)

Aren't you assuming a certain kind of guards, namely converting rather than throwing? There's no way to future-proof without more agreement on what the default meaning of x :: Number would be, and (AFAIK) we don't have consensus yet.

Anyway, no one is going to start writing imperative mouthfuls such as Object.guard(x, G) all over. That's not wanted. If guards arrive with compatible semantics, then people would have to plow through their code removing all such boilerplate in favor of guard syntax. But that's a best-case scenario.

Also, just on the number point: people don't all write x = Number(x). You'll see x = +x, or an application-specific conversion -- or no conversion at all (which could be a bug, but might not be due to constraints enforced elsewhere).

# Axel Rauschmayer (13 years ago)

Aren't you assuming a certain kind of guards, namely converting rather than throwing? There's no way to future-proof without more agreement on what the default meaning of x :: Number would be, and (AFAIK) we don't have consensus yet.

Yes, in the future of JavaScript, I’d expect more throwing and less converting.

Anyway, no one is going to start writing imperative mouthfuls such as Object.guard(x, G) all over. That's not wanted. If guards arrive with compatible semantics, then people would have to plow through their code removing all such boilerplate in favor of guard syntax. But that's a best-case scenario.

Also, just on the number point: people don't all write x = Number(x). You'll see x = +x, or an application-specific conversion -- or no conversion at all (which could be a bug, but might not be due to constraints enforced elsewhere).

My main points are: I think the JS programming style is going to change from converting to throwing. IMHO, that would be positive, it would reveal errors more quickly. If that is true then can/should we prepare for this and how?

I’d still favor the simplest possible type guards for ES.next, with the option of more features in the future.

Apart from something imperative, I can also imagine tools turning JSDoc-style type comments into runtime checks:

function add(/number/ x, /number/ y) { ... }

Most of Dart’s type system is much closer to JavaScript + minimal type guards than I initially thought. That’s a part of it I really like.