是否可以创建一个不仅可以验证而且还可以转换给定值的 Runtype
?
例如,检查正数:
import * as RT from "runtypes"
const PositiveOrFail = RT.Number.withConstraint(n => n >= 0)
但是,是否可以改为“默认”为一个值?
const PositiveOrClamp = RT.Number.???(n => (n >= 0) ? n : 0)
// Or another practical example:
const StringOrMissing = RT.String.optional().???(s => s ? s : "(missing)")
答案 0 :(得分:1)
目前没有。不过,它有一个 PR 草案。
/**
* example not currently released!!
*/
const Input = Record({
date: String.withTransform(s => {
const date = new Date(s);
if (isNaN(date.valueOf())) throw new Error(`Invalid date string "${s}"`);
else return date;
}),
});
type Input = Static<typeof Input>;
// { date: Date; }
Input.check({ date: 'crap' });
// ValidationError: Failed transform: Error: Invalid date string "crap" in date
const input: Input = Input.check({ date: '1990-01-01' });
console.log(input.date.toUTCString());
// Mon, 01 Jan 1990 00:00:00 GMT