【发布时间】:2017-03-13 08:12:52
【问题描述】:
我正在尝试使用 disjoint unions 在 Flow 中模拟 Scala 的 sealed case classes:
type ADD_TODO = {
type:'ADD_TODO',
text:string,
id:number
}
type TOGGLE_TODO = {type:'TOGGLE_TODO', id:number }
type TodoActionTy = ADD_TODO | TOGGLE_TODO
const todo = (todo:TodoTy, action:TodoActionTy) => {
switch (action.type){
case 'ADD_TODO' :
return { id:action.id, text:action.text, completed: false};
case 'TOGGGGLE_TODO': // this should give a type error
if (todo.id !== action.id) {return todo;}
return {...todo, completed:!todo.completed};
}
}
我应该得到case 'TOGGGGLE_TODO': 的类型错误,但我没有。
有没有办法解决这个问题?
编辑:
我将 Gabriele 评论中的代码粘贴到此处,以确保未来不会受到影响:
type TodoTy = {};
type ADD_TODO = { type: 'ADD_TODO', text: string, id: number };
type TOGGLE_TODO = { type: 'TOGGLE_TODO', id: number };
type TodoActionTy = ADD_TODO | TOGGLE_TODO;
export const todo = (todo: TodoTy, action: TodoActionTy) => {
switch (action.type){
case 'ADD_TODO': break;
// Uncomment this line to make the match exaustive and make flow typecheck
//case 'TOGGLE_TODO': break;
default: (action: empty)
}
}
【问题讨论】:
-
如果没有这个,有没有办法让流量检查详尽无遗?这感觉就像把负担放在程序员身上……
标签: javascript scala flowtype