-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathbasic_usage.mjs
More file actions
56 lines (49 loc) · 1.46 KB
/
basic_usage.mjs
File metadata and controls
56 lines (49 loc) · 1.46 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import typed from '../src/typed-function.mjs';
// create a typed function
var fn1 = typed({
'number, string': function (a, b) {
return 'a is a number, b is a string';
}
});
// create a typed function with multiple types per argument (type union)
var fn2 = typed({
'string, number | boolean': function (a, b) {
return 'a is a string, b is a number or a boolean';
}
});
// create a typed function with any type argument
var fn3 = typed({
'string, any': function (a, b) {
return 'a is a string, b can be anything';
}
});
// create a typed function with multiple signatures
var fn4 = typed({
'number': function (a) {
return 'a is a number';
},
'number, boolean': function (a, b) {
return 'a is a number, b is a boolean';
},
'number, number': function (a, b) {
return 'a is a number, b is a number';
}
});
// create a typed function from a plain function with signature
function fnPlain(a, b) {
return 'a is a number, b is a string';
}
fnPlain.signature = 'number, string';
var fn5 = typed(fnPlain);
// use the functions
console.log(fn1(2, 'foo')); // outputs 'a is a number, b is a string'
console.log(fn4(2)); // outputs 'a is a number'
// calling the function with a non-supported type signature will throw an error
try {
fn2('hello', 'world');
}
catch (err) {
console.log(err.toString());
// outputs: TypeError: Unexpected type of argument.
// Expected: number or boolean, actual: string, index: 1.
}