Skip to content

Optional function type annotations? #2551

Closed
@srackham

Description

@srackham

Function argument and return type declarations are a big help when it comes to reading and maintaining code, they also simplify IDE language tooling. ECMAScript 4.0 style function and union type annotations could be useful in this regard.

Syntax additions would be minimal: Function arguments and return values are annotated by appending a colon character followed a type name, where type names can be primitive type names, null, undefined or constructor names (CoffeeScript class names). Examples:

square = (x:number):number -> x * x
lineTo = (p:Point) ->
foobar = ():(number,null) -> # Returns number or null (union type annotation).

A minimal implementation (a documentary feature for humans and for tooling) would not require any changes to the code emitted by the compiler. The compiler would tolerate, but otherwise ignore, the type annotations.

Establishing a type declaration syntax also opens the door to more ambitious uses, for example a compiler option to generate runtime assertions (logging and/or exception throwing) to verify function argument types and function return value types.

Similar proposals have previously been mooted (see issues 1833, 116, 52). The scope of this proposal is more modest, the emphasis is on documentation and tooling rather than formal type checking and it would not alter the generated JavaScript or the language semantics.

So why not just embed the annotations in function comments? Because doc-comment style annotations would be much more verbose (and ugly) and would be textually disjoint from the function declaration (harder to read) and more prone to get out of sync with the implementation. Since they are not part of the language doc-comment annotations would be less likely to be adopted by tool developers.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions