基本数据类型:
types.string(字符串),types.number(数值),types.boolean(布尔),types.integer(整型),types.Date(日期,时间戳或date对象),types.null(null类型),types.undefined(..)
复杂数据类型:
types.model(对象类型),types.array(数组类型),
types.map(map类型,key是字符串,值为指定类型), 例: types.map(types.number) => {'0':1}
types.optional(可选类型,是一个方法,参数1:定义类型,参数2:默认值): 例:types.optional(types.number,1),types.optional(types.array(types.number), []);
types.custom(自定义类型):例如:
const MyDecimal = types.custom<string, Decimal>({
/** Friendly name */
name:string;
/** given a serialized value and environment, how to turn it into the target type */
fromSnapshot(snapshot:S,env?:any):T;
/** return the serialization of the current value */
toSnapshot(value:T):S;
/** if true, this is a converted value, if false, it's a snapshot */
isTargetType(value:T|S):boolean;
/** a non empty string is assumed to be a validation error */
getValidationMessage(snapshot:S):string;
})
types.union(联合类型), 例:types.union(types.number, types.string)
types.literal(字面值类型) 例: types.literal('abc'), types.literal(null), types.literal(undefined)
types.enumeration(枚举类型)例:types.enumeration('gender',['male']); 参数1:枚举类型名称, 参数2:枚举数组
types.maybe(可以undefined) 例: types.optional(types.union(types.string,types.literal(null)),null) === types.maybe(types.string)
types.maybeNull(可以null)
types.frozen(冻结的,定义不可编辑数据,属性变化不会引起相应状态更新) 例: types.model('store',{data:types.frozen() })
types.late(滞后类型,内部是一个方法) 例: types.model('A',{ a:types.maybe(types.late(() => A))})
types.refinement(提纯类型,定义字段,添加额外校验规则) 例: const EmailType = types.refinement('Email',types.string,(snapshot) =>/^[a-zA-Z_1-9]+@\.[a-z]+/.test(snapshot))
引用类型,标识符
types.identifier (唯一的)
types.identifierNumber(唯一的number类型)
types.reference(引用类型进行跟踪,设定值关联相同id对应obj, 可以设置diergobj参数自定义查找)
types.safeReference(安全的引用,如果对应obj删掉,那么重置undefined)
reference实现safeReference:
constselfSafeReference = types.maybeNull( types.reference(Product, {get(id: number, parent: Instance){returnparent.products.find(p=>p.id === id) ||undefined},set(value: Instance){returnvalue.id } }))
ts可能遇到的问题解决方案: 实例的快照:cast(store) ,快照的实例: castToSnapShot(store)
网友评论