sti*_*naq 6 javascript flowtype
我有一个函数foo,它接受两个数组的并集,它唯一做的就是遍历数组,但是我得到了流式错误,数组中缺少一些属性.是不是可以这样做?我根本没有使用任何属性.它们都是数组,因此流应该知道它们是可迭代的.
type Handle = {|
+articleId: string,
+type: 'handle',
+accessories: Array<string>,
+positionInfo: string,
|};
type Leg = {|
+articleId: string,
+type: 'leg',
|};
type Entity = Handle | Leg;
function foo(entities: Array<Handle> | Array<Leg>) {
entities.forEach(() => {})
}
Run Code Online (Sandbox Code Playgroud)
您可以将数组键入为包含Entity对象(例如Array<Entity>),稍后可以对其进行细化。或者,您可以将输入键入为Array<Handle | Leg>,但由于您已经Entity定义了类型,因此我们应该使用它。
(尝试)
// I made these types writeable and non-exact since it
// doesn't seem to matter for the sake of this question.
// You can make them read-only and exact in your code if
// you want (and I personally would unless I had good
// reason not to).
type Handle = {
type: 'handle',
articleId: string,
accessories: Array<string>,
positionInfo: string,
}
type Leg = {
type: 'leg',
articleId: string,
}
type Entity = Handle | Leg;
function foo(entities: Array<Entity>) {
entities.forEach(entity => {
// At this point, flow knows that our `entity` variable
// either contains a Handle or a Leg (from the above
// definition of the `Entity` type.) We can use a
// refinement to figure out which one it is:
if (entity.type === 'leg') {
const {type, articleId} = entity
console.log("A leg", type, articleId)
} else if (entity.type === 'handle') {
const {type, articleId, positionInfo} = entity
console.log("A handle", type, articleId, positionInfo)
} else {
// We can even assert that we covered all possible
// cases by asserting that the `entity` value has
// no remaining union cases and is therefore empty
(entity: empty)
}
})
}
const entitiesExample = [
{articleId: 'blah', type: 'leg'},
{articleId: 'toot', type: 'handle', accessories: [], positionInfo: 'bar'}
]
foo(entitiesExample)
Run Code Online (Sandbox Code Playgroud)
==旁注:我注意到如果我使用属性检查type而不是上面的检查,流程在细化类型时会遇到麻烦===。如果有人知道那里发生了什么,我很想知道,因为我的直觉是这==应该可以正常工作。
| 归档时间: |
|
| 查看次数: |
282 次 |
| 最近记录: |