deftypes

type annotation DSL

Deftypes.js

JavaScript type annotaion DSL library for structure and function.

It is type checker on execution(not static).

Deftypes can avoid all side effects if you want. It may be also good on testing framework.

Examples are coffee-script.

$ npm install deftypes
{defdefunT} = require 'deftypes'
$ bower install deftypes
<script src="bower_components/deftypes/deftypes.js"></script>

or download deftypes.js of this directory

<script src="master/deftypes.js"></script>
Deftypes()

It provides DSLs => def, defun, T

Point = {x: Numbery: Number}
p1 = def Point{x:1y:2} #=> {x: 1, y:2} 
p2 = def Point{x:1z:2} #=> type error 
list = def [T.Int][1,2,3]

(T.Int and T.Fload are defined by default)

NullableNumber = {n: T.Nullable(Number)}
p1 = def NullableNumbern:1
p2 = def NullableNumbern:null
id_table = def T.Hash(StringNumber){
  A:1
  B:2
  C:3
}

Key accepts only Number or String (but it doesn't check yet)

check arguments and returned object

f1 = def T.Func([NumberNumber]String)(m, n) -> "#{m}#{n}"
f1(1,2) #=> "1, 2" 
f1("",2) #=> argument error 
find_index = def T.Func([[Number]Number]T.Nullable(Number))(arr, n) ->
  if (index = arr.indexOf(n)) is -1 then null else index
 
find_index([3,4,5]4) #=> 1 
find_index([3,4,5]9) #=> null 
f2 = defun [NumberNumber]String(m, n) -> "#{m}#{n}"
events = def Objectrequire('events')
list = def [T.any][0""null]
= def Point{x:1y:2}
def Pointp->
  @x = 3
 
# Type Error 
def Pointp-> @y = "not number"

if option.transparent is true, typechecker does nothing, passing through def like transparent for avoiding performance down.

{option} = require 'deftypes'
option.transparent = true
Deftypes.option.transparent = true
  • trait feature
  • struct inheritance
  • valid error message