zerkms
zerkms

Reputation: 254926

Return type of a `yield call`

I've noticed that the result of a yield call effect is typed as any when used as

const data = yield call(f);

while f is a () => Promise<number> function.

Am I missing something or is it a redux-saga typings limitation?

Upvotes: 14

Views: 18988

Answers (4)

Jan Jarč&#237;k
Jan Jarč&#237;k

Reputation: 2901

You can use

const data = (yield call(f)) as number

Upvotes: 0

redbuck
redbuck

Reputation: 11

define this types

export type PromiseFn = (...args: any) => Promise<any>;
export type GetT<T> = T extends Promise<infer N> ? N : any;
export type GetFnResult<T extends PromiseFn> = GetT<ReturnType<T>>;

then

const data: GetFnResult<typeof f> = yield call(f);

Upvotes: 1

NearHuscarl
NearHuscarl

Reputation: 81390

In the meantime, you can use this package instead: typed-redux-saga

Before

import { call, all } from "redux-saga/effects";
...
// Api.fetchUser return User
// but user has type any
const user = yield call(Api.fetchUser, action.payload.userId);

After

import { call, all } from "typed-redux-saga";
...
// user now has the correct type User
// NOTE: it's yield*, not yield
const user = yield* call(Api.fetchUser, action.payload.userId);

Upvotes: 5

Karen Grigoryan
Karen Grigoryan

Reputation: 5432

Check this ongoing thread, tldr; it's a typescript limitation

Upvotes: 12

Related Questions