maybeConvert
Create a converting TypeObject that also accepts null
and undefined
.
type.maybe(Type)
Given a type, returns a TypeObject that will check values against that type. Coerces if the value is not of the provided type or null
or undefined
.
import { Reflect, type } from "can/everything";
let val = Reflect.convert(42, type.maybeConvert(Number));
console.log(val); // -> 42
val = Reflect.convert(null, type.maybeConvert(Number));
console.log(val); // -> null
val = Reflect.convert(undefined, type.maybeConvert(Number));
console.log(val); // -> undefined
val = Reflect.convert("42", type.maybeConvert(Number));
console.log(val); // -> 42
Parameters
- Type
{function}
:A constructor function that values will be checked against.