Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare TypeScript object interface that has exact fields and any extra properties

Tags:

typescript

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.

like image 280
ValeriiVasin Avatar asked May 18 '16 10:05

ValeriiVasin


1 Answers

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).

like image 109
Nitzan Tomer Avatar answered Sep 20 '22 15:09

Nitzan Tomer