【问题标题】:sealed case classes in flow流程中的密封案例类
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 真的吗?我不这么认为,'因为case 'TOGGGGLE_TODO': 仍在进行类型检查。
  • 你是什么意思?使用TOGGGGLE_TODO时可以看到以下错误:(action: empty) object type. This type is incompatible with empty (Flow v0.34)
  • 有趣!谢谢 !我一时糊涂了。
  • 如果我尝试你的建议,我会得到:identifier empty Could not resolve name
  • 你可以简单地使用 null 而不是 empty
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
相关资源
最近更新 更多