转换值的运行类型



是否可以创建一个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)")

当前没有。不过,它有一份公关草案。

/**
* 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

https://github.com/pelotom/runtypes/pull/191

https://github.com/pelotom/runtypes/issues/56

最新更新