basic_usage.js (1488B)
1 var typed = require('../typed-function'); 2 3 // create a typed function 4 var fn1 = typed({ 5 'number, string': function (a, b) { 6 return 'a is a number, b is a string'; 7 } 8 }); 9 10 // create a typed function with multiple types per argument (type union) 11 var fn2 = typed({ 12 'string, number | boolean': function (a, b) { 13 return 'a is a string, b is a number or a boolean'; 14 } 15 }); 16 17 // create a typed function with any type argument 18 var fn3 = typed({ 19 'string, any': function (a, b) { 20 return 'a is a string, b can be anything'; 21 } 22 }); 23 24 // create a typed function with multiple signatures 25 var fn4 = typed({ 26 'number': function (a) { 27 return 'a is a number'; 28 }, 29 'number, boolean': function (a, b) { 30 return 'a is a number, b is a boolean'; 31 }, 32 'number, number': function (a, b) { 33 return 'a is a number, b is a number'; 34 } 35 }); 36 37 // create a typed function from a plain function with signature 38 function fnPlain(a, b) { 39 return 'a is a number, b is a string'; 40 } 41 fnPlain.signature = 'number, string'; 42 var fn5 = typed(fnPlain); 43 44 // use the functions 45 console.log(fn1(2, 'foo')); // outputs 'a is a number, b is a string' 46 console.log(fn4(2)); // outputs 'a is a number' 47 48 // calling the function with a non-supported type signature will throw an error 49 try { 50 fn2('hello', 'world'); 51 } 52 catch (err) { 53 console.log(err.toString()); 54 // outputs: TypeError: Unexpected type of argument. 55 // Expected: number or boolean, actual: string, index: 1. 56 }