Flow JS-如何在对象中将泛型用作带有类的映射

时间:2018-12-28 17:43:31

标签: flowtype

我有以下课程:

// @flow

type Entities<EntityType> = {
    [number]: EntityType
}

export default class NormalizedCollection<EntityType> {
    entities: Entities<EntityType>
    result: Array<number>

    constructor(entities: Entities<EntityType>, result: Array<number>) {
        this.entities = entities
        this.result = result
    }

    getItems = (): Array<Object> => {
        try {
            if (this.result) {
                return this.result.map((index, key) => this.entities[index]).filter((item)=>typeof item !== 'undefined')
            }
        } catch (e) {}

        return []
    }

    find = (id: number): Entities<EntityType> | null =>  {
        if(typeof this.entities === 'undefined' || typeof this.entities[id] === 'undefined') {
            return null
        }
        return this.entities[id]
    }
}

该类具有两个参数,实体(作为地图的对象)和结果(其为数字数组)。我希望该类的使用者能够指出他们正在传递的实体类型。

这给了我两个错误。

从getItems:

Cannot return this.result.map(...).filter(...) because EntityType [1] is incompatible with object type [2] in array element.

来自查找:

Cannot return this.entities[id] because EntityType [1] is incompatible with Entities [2]

将实体类型传递给NormalizedCollection的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我忘记更改退货类型! (分别为Array<EntityType>EntityType

// @flow

type Entities<EntityType> = {
    [id: number]: EntityType
}

export default class NormalizedCollection<EntityType> {
    entities: Entities<EntityType>
    result: Array<number>

    constructor(entities: Entities<EntityType>, result: Array<number>) {
        this.entities = entities
        this.result = result
    }

    getItems = (): Array<EntityType> => {
        try {
            if (this.result) {
                return this.result.map(index => this.entities[index]).filter((item)=>typeof item !== 'undefined')
            }
        } catch (e) {}

        return []
    }

    find = (id: number): EntityType | null =>  {
        if(typeof this.entities === 'undefined' || typeof this.entities[id] === 'undefined') {
            return null
        }
        return this.entities[id]
    }
}