密封的案例类流程

jhe*_*dus 6 javascript scala flowtype

我试图通过使用不相交的联合来模拟Scala 在Flow中的密封案例类:

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};
  }
}
Run Code Online (Sandbox Code Playgroud)

我应该得到一个类型错误,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)
  }
}
Run Code Online (Sandbox Code Playgroud)

gca*_*nti 6

empty类型可用于验证Flow确信详尽无遗

export const todo = (todo: TodoTy, action: TodoActionTy) => {
  switch (action.type){
    case 'ADD_TODO' :
      ...
    case 'TOGGGGLE_TODO':
      ...
    default :
      // only true if we handled all cases
      (action: empty)
      // (optional) handle return type
      throw 'unknown action'
  }
}
Run Code Online (Sandbox Code Playgroud)