Redux-saga:如何使用 typeScript 键入 worker 的参数
Redux-saga: How to type worker's parameter with typeScript
有什么方法可以使用 typescript 来设置 worker saga 的参数类型吗?
我有这个界面
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.
有什么想法吗?
如果问题仍然相关,这里就是答案。
你应该定义一些从 redux 扩展 Action
的接口,然后将它作为类型参数传递给 takeEvery
。这将正确键入 worker 函数。
// 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
// }
有什么方法可以使用 typescript 来设置 worker saga 的参数类型吗?
我有这个界面
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.
有什么想法吗?
如果问题仍然相关,这里就是答案。
你应该定义一些从 redux 扩展 Action
的接口,然后将它作为类型参数传递给 takeEvery
。这将正确键入 worker 函数。
// 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
// }