maybeConvert
Create a converting TypeObject that also accepts null
and undefined
.
type.maybeConvert(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 { ObservableObject, type } from "can";
class Person extends ObservableObject {
static props = {
age: maybeConvert(Number)
};
}
let person = new Person();
person.age = 42; // -> 42
person.age = null; // -> null
person.age = undefined; // -> undefined
person.age = "42"; // -> 42
Parameters
- Type
{function}
:A constructor function that values will be checked against.
Use Case
Like with convert, type.maybeConvert is particularly useful when building models for service layers (like with can-rest-model and can-realtime-rest-model. Some server-side data layers will transfer empty values in database as either null
or undefined
. Using type.maybeConvert will prevent these values from throwing, but also attempt to convert them when a value does exist.