types

Brendan Eich brendan at mozilla.org
Thu Aug 14 12:30:28 PDT 2008


On Aug 14, 2008, at 10:40 AM, Steven Johnson wrote:

> On 8/14/08 6:25 AM, "Neil Mix" <nmix at pandora.com> wrote:
>> It sounds like static type checking infers a certain
>> amount of "hard failure," i.e. you can't run this until you fix your
>> code.  That's not really what I'm voting for.  I just want it to be
>> possible, somehow, to catch simple type errors very early in the
>> development process, and then to run the same type annotated code
>> unchanged in the browser.
>
> Depends on what you mean by "hard failure". If we have a function like
>
>     // n must be a numeric type
>     function sqrt(n) { ... }
>
> then the ability to say
>
>     function sqrt(n:Number) { ... }
>
> only requires that n by convertible-to-Number at runtime. (If not,  
> ES4/AS3
> required that a TypeError be thrown.)


That allows sqrt("foo") to compute the square root of a NaN, which is  
a NaN.

For this reason, ES4 last year moved to avoid implicit conversions  
except among number types.


> This does make it possible to do some static type checking at  
> compile-time,
> of course (and the AS3 compiler can optionally do this).

IIRC that's because AS3's strict mode (a static type checker) changes  
the rules to avoid the implicit conversion (from the standard or  
dynamic mode, which converts freely as you say). May be water under  
the bridge, but at least for ES4 we chose to get rid of the strict  
vs. standard implicit conversion difference, and require a number in  
both.


> Personally, I like catching stupid mistakes of this sort as early as
> possible, so I tend to use type annotations everywhere I can when I  
> code in
> AS3. Your mileage may vary.

There are pluses and minuses. We've all been saved by simple types in  
C, compared to assembly or pre-historic C which allowed int and  
pointers to convert, and treated struct member names as offset macros  
usable with any int or pointer. But JS is a higher level language,  
and one doesn't need to annotate types to avoid memory safety bugs.  
For numeric code, there can even be a de-optimizing effect if one  
uses int or uint in AS3, I'm told, because evaluation still promotes  
everything to Number (double). Is this right?

I took Neil's point to favor not only a separate lint-like tool  
(which some find painful to procure and remember to run), but  
possibly something like Cormac's idea I mentioned a few messages ago:  
a type checker that runs when the code loaded in a web app seems  
complete, and gives warnings to some console -- but which does not  
prevent code from running.

Neil, how'd that strike you? It could be built into some developer- 
extension for the browser, so you wouldn't have to remember to run  
jslint.

/be




More information about the Es-discuss mailing list