Redux-Saga:如何使用TypeScript键入worker的参数

时间:2019-10-23 13:01:33

标签: typescript redux-saga worker

有没有办法使用Typescript来设置worker传奇的参数类型?

我有这个界面

interface ITask{
    id: number
    task: string,
    //other things here
}

我有这个听众和工作人员:

function* addTaskSaga():any {
    yield takeEvery("TASK_ADD", workerAddTaskSaga);
}
function* workerAddTaskSaga({data}:any) {
  //other things here
}

此代码运行良好,但是我想强类型化worker的参数,我的意思是:将{data}:any更改为data:ITask

但是这会引发异常:

The last overload gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'TakeableChannel<unknown>'.ts(2769)
effects.d.ts(207, 17): The last overload is declared here.

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果问题仍然很重要,这里就是答案。

您shuold定义了一些接口,该接口从redux扩展了Action,然后将其作为类型参数传递给takeEvery。这将正确键入辅助函数。

// This is Action interface which will hold type and payload. 
interface TaskAction extends Action, ITask {type: "TASK_ADD" }

// Alternatively you may use 
// interface TaskAction extends Action {type: "TASK_ADD", data: ITask }

interface ITask{
  id: number
  task: string,
  //other things here
}

function* addTaskSaga():any {
  yield takeEvery<TaskAction>("TASK_ADD", workerAddTaskSaga);
}

function* workerAddTaskSaga(data:TaskAction) {
  // data is of type TaskAction
  // data.id is number from ITask
  // data.task is string from ITask
}

// Or if you've chosen second form of TaskAction
//   function* workerAddTaskSaga({ data } : TaskAction) {
     // data is of type ITask
//   }