ts-cast
Version:
Runtime typechecking
12 lines (11 loc) • 543 B
JavaScript
import { withName } from '../helpers/names';
import { throwTypeError } from './throw-type-error';
const required = (typeName, typeGuard, transform) => withName((value, context, reportError = throwTypeError) => {
if (value === undefined || !typeGuard(value)) {
return reportError(`${typeName} is expected${context ? ` in ${context}` : ''} but "${value}" received.`, context);
}
return (typeof transform === 'function'
? transform(value, context, reportError)
: value);
}, typeName);
export default required;