Joj*_*oji 3 javascript ecmascript-6 flowtype flow-typed
伙计们,我是Flow新手。
我有这个代码
type importItem = {
name: string,
groupRank: number,
rank: number,
node: Object,
};
function findTargetImportItem(importedItems: Array<importItem>, outOfOrderItem: importItem) : importItem {
return importedItems.find((importedItem: importItem) => importedItem.rank > outOfOrderItem.rank);}
Run Code Online (Sandbox Code Playgroud)
我得到这个错误
Cannot return importedItems.find(...) because undefined [1] is incompatible with importItem [2].
src/rules/import-order.js
[2] 74? function findTargetImportItem(importedItems: Array<importItem>, outOfOrderItem: importItem) : importItem {
75? /**
76? * Return the import where the unordered imports will be moving towards
77? */
78? return importedItems.find((importedItem: importItem) => importedItem.rank > outOfOrderItem.rank);
79? }
80?
81? function hasTrailingSpace(sourceCode, node) {
/private/tmp/flow/flowlib_21840530/core.js
[1] 244? find(callbackfn: (value: T, index: number, array: Array<T>) => any, thisArg?: any): T | void;
Run Code Online (Sandbox Code Playgroud)
我不知道如何使Flow知道由find helper函数返回的东西是importItem类型。
你们能帮我吗
流编译器是正确的。它知道所返回的值find() 可以是undefined。
如果数组中的所有项目都不满足您传递的回调中的条件,则返回值为undefined。要么改变你的返回类型findTargetImportItem()来void | importItem或返回值分配find()给一个临时变量和返回类型的某些默认值importItem如果临时变量undefined。
function findTargetImportItem(importedItems: Array<importItem>, outOfOrderItem: importItem) : void | importItem {
/**
* Return the import where the unordered imports will be moving towards
*/
return importedItems.find((importedItem: importItem) => importedItem.rank > outOfOrderItem.rank);
}
Run Code Online (Sandbox Code Playgroud)
const defaultImportItem: importItem = ...;
function findTargetImportItem(importedItems: Array<importItem>, outOfOrderItem: importItem) : importItem {
/**
* Return the import where the unordered imports will be moving towards
*/
const importedItem = importedItems.find((importedItem: importItem) => importedItem.rank > outOfOrderItem.rank);
return importedItem === undefined
? defaultImportItem
: importedItem;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
217 次 |
| 最近记录: |