2016-08-20 89 views
10

什麼是適當的方式處理Map中的對象?ES6 Map of Flowtype

const animals:Map<id, Animal> = new Map(); 

function feedAnimal(cageNumber:number) { 
    const animal:Animal = animals.get(cageNumber); 

    ... 
} 

錯誤

const animal:Animal = animals.get(cageNumber); 
         ^^^^^^^^^^^^^^^^^^^^^^^^ call of method `get` 

const animal:Animal = animals.get(cageNumber); 
         ^^^^^^^^^^^^^^^^^^^^^^^^ undefined. This type is incompatible with 
const animal:Animal = animals.get(cageNumber); 
         ^^^^^^^ Animal 

Flowtype Map declaration

回答

11

animals.get(cageNumber)類型爲?Animal,不Animal。你需要檢查,它不是未定義:

function feedAnimal(cageNumber:number) { 
    const animal = animals.get(cageNumber); 

    if (!animal) { 
    return; 
    } 
    // ... 
} 
+0

新增更新 – vkurchatkin

+0

如果唯一的目標就是永遠不會有'void',那麼你也可以用'如果(animals.has(cageNumber))'哪個更可讀(可能更快,因爲你沒有分配任何東西來刪除它們)。 但我不知道如何返回正確的類型,即'動物'。根據流你的解決方案和我的兩個返回類型是'void | Animal'。這是有道理的,因爲你可能不希望Flow猜測你的代碼做了什麼,因此返回類型等於'動物'的類型。 如果有人有解決這個問題,我很感興趣。 –