我正在尝试使用sealed case classes在Flow中模拟Scala的disjoint unions:

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)
  }
}

最佳答案

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'
  }
}

关于javascript - 密封箱类流动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40338895/

10-13 02:14