在交叉点类型上调用.map()

时间:2017-11-17 17:04:31

标签: javascript flowtype

我为JSON API对象创建了类型定义:

type CommonCurrentJob = {
    id: number,
    qty: 29,
    qty_changed: 27,
    created_at: string,
    updated_at: string
}

type Job = {
    user_id: number,
    status: 'open' | 'closed',
    location: 'string',
    history: Array<{[number]: string}>,
    note: string,
}

type JobDetails = Array<{iaj_id: number, code: number}>;

type CurrentJob = {
    inventoryJob: Job & CommonCurrentJob,
    inventoryJobDetails: JobDetails & CommonCurrentJob
}

在fetch调用中,我正在json.inventoryJobDeails上执行映射:

 return fetch(url, {credentials: 'include'})
        .then((response) => {
            return response.json();
        })
        .then((json: CurrentJob) => {
            console.log(json);
            const location = json.inventoryJob.location;
            const ref_note = json.inventoryJob.note;
            const id = json.inventoryJob.id;
            const models = json.inventoryJobDetails.map((j) => {
                return Object.assign({}, {
                    code: j.code,
                    qty: j.qty
                })
            });
            this.setState({ currentCodes: models, location: location, ref_note: ref_note, id: id})
            return json
        })

错误流程给了我:

Error:(152, 32) Flow: call of method `map`. Method cannot be called on any member of intersection type intersection 

我是Flow新手,不明白为什么无法映射交集类型。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

loganfsmyth已在评论中解决了我的问题:

  

JobDetails & CommonCurrentJob是“一个数组类型”的组合   “具有属性的对象”,所以它是一个正常的数组   数字索引,它还具有索引旁边的属性。

所以我重构了我的代码来创建一个纯对象交集:

type CommonCurrentJob = {
    id: number,
    qty: 29,
    qty_changed: 27,
    created_at: string,
    updated_at: string
}

type Job = {
    user_id: number,
    status: 'open' | 'closed',
    location: 'string',
    history: {[number]: string}[],
    note: string,
    id: number,
    qty: 29,
    qty_changed: 27,
    created_at: string,
    updated_at: string
} & CommonCurrentJob;

type JobDetails = {
    iaj_id: number,
    code: number,
    id: number,
    qty: 29,
    qty_changed: 27,
    created_at: string,
    updated_at: string
} & CommonCurrentJob;

type CurrentJob = {
    inventoryJob: Job,
    inventoryJobDetails: JobDetails[]
}