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