-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-type.js
39 lines (37 loc) · 1011 Bytes
/
check-type.js
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
// @ts-check
const {Check} = require('./check.js');
const errorMessage = require('./error-message.js');
const fullTypeName = require('./full-type-name.js');
/**
* @template T
* @typedef {import("./base-types.js").t<T>} t
*/
/**
* @typedef {import("./base-types.js").AnyTypeOrShape} AnyTypeOrShape
*/
/**
* @typedef {import("./check-error.js").CheckError} CheckError
*/
/**
* @template {AnyTypeOrShape} T
* @param {t<T>} value an object to check, it can be of type 'any'.
* @param {T} type
* @returns {{ok:true, value:t<T>} | {ok:false, errors: CheckError[], errorMessage: string}}
*/
function checkType(value, type) {
const check = new Check();
if (!check.type(value, type)) {
return {
ok: false,
errors: check.errors,
get errorMessage() {
return (
`Error while checking ${fullTypeName(type)}\n` +
check.errors.map((err) => errorMessage(err)).join('\n')
);
},
};
}
return {ok: true, value};
}
module.exports = checkType;