nullException
nullException

Reputation: 1122

declare type in TypeScript based on the return type of a generator function

This is how i define an action using an ActionCreater and its Type.

   const listRequestAction = new ActionCreator<undefined, undefined>(
        REQUEST_LIST
      );
    
   type listRequestActionType = ReturnType<
        typeof listRequestAction.create
        >;

I wanted to add a dynamic namespace to my actions so I made this change to the action.

       const listRequestAction = (namespace: string) => 
          new ActionCreator<undefined, undefined>(
            `${namespace}${REQUEST_LIST}`
          );

how do i redefine listRequestActionType to support the namespace change?

Upvotes: 1

Views: 72

Answers (1)

Gerrit Begher
Gerrit Begher

Reputation: 403

This is only possible in TS 4.2 and higher. (https://github.com/Microsoft/TypeScript/wiki/Roadmap)

Playground link. Seems a bit verbose, though. Feel free to refactor it.

// Is this the correct reference? https://github.com/cameronmaske/react-redux-typescript
class ActionCreator<T, P> {
    readonly type: T;

    constructor(type: T) { this.type = type; }
    create = (payload: P) => ({ type: this.type, payload });
}


// I assume `REQUEST_LIST` is a string constant?
const REQUEST_LIST: "REQUEST_LIST" = "REQUEST_LIST"


const listRequestAction = <P, Namespace extends string>(
    namespace: Namespace
    ): ActionCreator<`${Namespace}${typeof REQUEST_LIST}`, P> =>
        new ActionCreator(
            `${namespace}${REQUEST_LIST}` as `${Namespace}${typeof REQUEST_LIST}`
        )

type listRequestActionType<P, Namespace extends string> = ReturnType<
    ActionCreator<`${Namespace}${typeof REQUEST_LIST}`, P>["create"]
>;

Upvotes: 1

Related Questions