Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Isnt createAction type parameter redundant when creatorFunction used? #18

Closed
CzBuCHi opened this issue Mar 7, 2018 · 2 comments
Closed

Comments

@CzBuCHi
Copy link

CzBuCHi commented Mar 7, 2018

Why createAction(string, fn) has first parameter pressent? Because i dont see difference between these two:

type TYPE = (param: any) => { type: "AAA", payload: { param: any } };

// yours
const action: TYPE = createAction("AAA", (param: any) => ({
  payload: { param },
  type: "AAA",
}));

// mine defined bellow
const action: TYPE = createAction2((param: any) => ({
  payload: { param },
  type: "AAA",
}));

export function createAction2<T extends string, AC extends (...args: any[]) => FluxStandardAction<T>>(
  creator: T | AC,
): AC & TypeGetter<T> {
  let type: T;
  let actionCreator: AC & TypeGetter<T>;

  if (typeof creator === 'string') {
    actionCreator = (() => ({ type })) as AC & TypeGetter<T>;
    type = creator;
  } else if (typeof creator === 'function') {
    actionCreator = creator as AC & TypeGetter<T>;
    type = actionCreator().type;
  } else {
    throw new Error('argument must be of type string or function');
  }

  (actionCreator as TypeGetter<T>).getType = () => type;
  return actionCreator;
}

only thing, that is funky is calling creatorFunction to determine action type ...

Why? Lazynest :) - currenly i need to write action type twice ....

PS: Tryied to create PR, but same code fails to compile in fork project (compiles in my test project)

@piotrwitek
Copy link
Owner

piotrwitek commented Mar 7, 2018

The problem is this:

// yours really is these two together
type TYPE = (param: any) => { type: "AAA", payload: { param: any } };
// +
const action: TYPE = createAction2((param: any) => ({
  payload: { param },
  type: "AAA",
}));

// mine is really only a decorator - I do not need the extra TYPE declaration which is twice more boilerplate
// moreover I will get rid of first param in TS 2.8 :) double win
const action = createAction("AAA", (param: any) => ({
  payload: { param },
  type: "AAA",
}));

@CzBuCHi
Copy link
Author

CzBuCHi commented Mar 8, 2018

thx for explaining this - btw: i used TYPE only to validate creataAction return type ... didnt check "real" return type of my fn ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants