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
Typeis a primitive likeNumber,String,Boolean, thevaluewill be passed to theTypefunction 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
Typehas acan.isMembersymbol value, that value will be used to determine if thevalueis already an instance. - If the
Typeis a isConstructorLike function,instanceof Typewill be used to check ifvalueis already an instance.
- If the
- If
valueis already an instance,valuewill be returned. - If
Typehas acan.newsymbol,valuewill be passed to it and the result returned. - If
Typeis a isConstructorLike function,new Type(value)will be called the the result returned. - If
Typeis 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.