6

I do have some problems with declaration of Redux Action Type. By definition the Redux Action should have type property and could have some other properties.

According to TypeScript interfaces page in HandBook (see "Excess Property Checks") i could do it like that:

interface IReduxAction {
  type: string;
  [propName: string]: any;
}

And seems it work in some situations (like declaration of a variable)

const action: IReduxAction = {
  type: 'hello',
  value: 'world'
};

But if i am trying to declare function that is using the action:

function hello(state = {}, action: IReduxAction) {
  return { type: action.type, text: action.text };
}

It fails with the message "Property text does not exist on type IReduxAction".

What am i doing wrong? How to declare the general action type?

Live example on TypeScript playground is here

P.S. I checked "similar" questions, like Why am I getting an error "Object literal may only specify known properties"?, and haven't found the solution there...

P.S.S. Apparently it does work in latest version of TypeScript.

ValeriiVasin
  • 8,628
  • 11
  • 58
  • 78

1 Answers1

2

In that same page you referenced it talks about it in the section titled Indexable Types.

You'll need to do this:

function hello(state = {}, action: IReduxAction) {
    return { type: action.type, text: action["text"] };
}

As your interface definition is defined to have index from string (key) to any (value).

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • 1
    I read that section as well. And with your changes it works fine. The problem is - i don't want to use non-dot notation here. Its normal JavaScript notation and it should be possible to make it work somehow... The question is - how? – ValeriiVasin May 18 '16 at 13:31
  • As far as I know you can't, that's how typescript differentiate between known fields and indexable ones. – Nitzan Tomer May 18 '16 at 13:35