convert
Convert one value to another type.
convert(value, Type)
convert
attempts to convert value
to the type specified by Type
.
import canRefect from "can-reflect";
canReflect.convert("1", Number) //-> 1
convert
works by performing the following logic:
- If the
Type
is a primitive likeNumber
,String
,Boolean
, thevalue
will be passed to theType
function and the result returned.return Type(value);
- The value will be checked if it is already an instance of the type
by performing the following:
- If the
Type
has acan.isMember
symbol value, that value will be used to determine if thevalue
is already an instance. - If the
Type
is a isConstructorLike function,instanceof Type
will be used to check ifvalue
is already an instance.
- If the
- If
value
is already an instance,value
will be returned. - If
Type
has acan.new
symbol,value
will be passed to it and the result returned. - If
Type
is a isConstructorLike function,new Type(value)
will be called the the result returned. - If
Type
is a regular function,Type(value)
will be called and the result returned. - If a value hasn't been returned, an error is thrown.
Parameters
- value
{Object|Primitive}
:A value to be converted.
- Type
{Object|function}
:A constructor function or an object that implements the necessary symbols.
Returns
{Object}
:
The value
converted to a member of Type
.