我对Redux Action Type的声明确实存在一些问题。根据定义,Redux Action 应该具有type
属性,而可以具有其他一些属性。
根据TypeScript interfaces page in HandBook(参见“超额财产检查”),我可以这样做:
interface IReduxAction {
type: string;
[propName: string]: any;
}
似乎在某些情况下(如声明变量)
const action: IReduxAction = {
type: 'hello',
value: 'world'
};
但是,如果我试图声明正在使用该操作的函数:
function hello(state = {}, action: IReduxAction) {
return { type: action.type, text: action.text };
}
它失败,并显示“text
类型上不存在属性IReduxAction
”。
我做错了什么?如何声明一般动作类型?
TypeScript playground上的实例是here
P.S。我查看了“类似”的问题,比如Why am I getting an error "Object literal may only specify known properties"?,并且没有在那里找到解决方案...
P.S.S。显然确实在最新版本的TypeScript中工作。
答案 0 :(得分:2)
在您引用的同一页面中,它在标题为Indexable Types
的部分中讨论了它。
你需要这样做:
function hello(state = {}, action: IReduxAction) {
return { type: action.type, text: action["text"] };
}
由于您的接口定义被定义为具有从字符串(键)到任何(值)的索引。