custom_type.js (878B)
1 var typed = require('../typed-function'); 2 3 // create a prototype 4 function Person(params) { 5 this.name = params.name; 6 this.age = params.age; 7 } 8 9 // register a test for this new type 10 typed.addType({ 11 name: 'Person', 12 test: function (x) { 13 return x instanceof Person; 14 } 15 }); 16 17 // create a typed function 18 var stringify = typed({ 19 'Person': function (person) { 20 return JSON.stringify(person); 21 } 22 }); 23 24 // use the function 25 var person = new Person({name: 'John', age: 28}); 26 27 console.log(stringify(person)); 28 // outputs: '{"name":"John","age":28}' 29 30 // calling the function with a non-supported type signature will throw an error 31 try { 32 stringify('ooops'); 33 } 34 catch (err) { 35 console.log('Wrong input will throw an error:'); 36 console.log(' ' + err.toString()); 37 // outputs: TypeError: Unexpected type of argument (expected: Person, 38 // actual: string, index: 0) 39 }