不能在 mobx-state-tree 数组上做 forEach
cannot do forEach on mobx-state-tree array
我正在尝试使用 typescript 和 MobX-state-tree 组织我的新项目
但我遇到了一个小问题
在服务函数中,我需要遍历存储在我的一个模型中的 MST 数组
这是此模型的示例
export const ValueHolder = types.model("ValueHolder", {
identifier: types.maybeNull(types.union(types.number, types.string))
});
export const Results = types.model("Results", {
locations: types.array(ValueHolder)
});
和我的服务功能
sendLocationNotification(locations: ValueHolderArrayType) {
locations.forEach(function (locationResult) {
});
}
Typescript 类型定义如下
export type ValueHolderArrayType = IArrayType<typeof ValueHolder>;
export type ValueHolderType = Instance<typeof ValueHolder>;
但这会导致 TS2339: Property 'forEach' does not exist on type 'ValueHolderArrayType'.
我可以看到 IArrayType 是从 IType 扩展的,它包含 IMSTArray,它在根部是从 js 数组类型扩展而来的,所以它应该有 forEach 签名。显然,我做错了什么,但在学习之后我找不到我的错误。我认为是我输入的错误。
您能否指导我如何编写类型,以便我能够遍历 MST 数组?
谢谢
我不能遗憾地告诉你为什么 export type ValueHolderArrayType = IArrayType<typeof ValueHolder>;
不起作用,因为我以前从未明确使用过 IArrayType
,但你可以将 locations
注释为 [= 的数组14=] 它将起作用:
sendLocationNotification(locations: ValueHolderType[]) {
locations.forEach(function (locationResult) {
// ...
});
}
我正在尝试使用 typescript 和 MobX-state-tree 组织我的新项目 但我遇到了一个小问题 在服务函数中,我需要遍历存储在我的一个模型中的 MST 数组
这是此模型的示例
export const ValueHolder = types.model("ValueHolder", {
identifier: types.maybeNull(types.union(types.number, types.string))
});
export const Results = types.model("Results", {
locations: types.array(ValueHolder)
});
和我的服务功能
sendLocationNotification(locations: ValueHolderArrayType) {
locations.forEach(function (locationResult) {
});
}
Typescript 类型定义如下
export type ValueHolderArrayType = IArrayType<typeof ValueHolder>;
export type ValueHolderType = Instance<typeof ValueHolder>;
但这会导致 TS2339: Property 'forEach' does not exist on type 'ValueHolderArrayType'.
我可以看到 IArrayType 是从 IType 扩展的,它包含 IMSTArray,它在根部是从 js 数组类型扩展而来的,所以它应该有 forEach 签名。显然,我做错了什么,但在学习之后我找不到我的错误。我认为是我输入的错误。
您能否指导我如何编写类型,以便我能够遍历 MST 数组?
谢谢
我不能遗憾地告诉你为什么 export type ValueHolderArrayType = IArrayType<typeof ValueHolder>;
不起作用,因为我以前从未明确使用过 IArrayType
,但你可以将 locations
注释为 [= 的数组14=] 它将起作用:
sendLocationNotification(locations: ValueHolderType[]) {
locations.forEach(function (locationResult) {
// ...
});
}