我在声明 Redux Action 类型时确实遇到了一些问题。根据定义,Redux Action 应该具有type
属性并且可以具有一些其他属性。
根据 TypeScript interfaces page in HandBook (参见“超额属性(property)检查”)我可以这样做:
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 };
}
失败并显示消息“IReduxAction
上不存在属性 text
”。
我做错了什么?如何声明通用 Action 类型?
TypeScript playground 上的实例是 here
附言我检查了“类似”的问题,比如 Why am I getting an error "Object literal may only specify known properties"? ,并没有在那里找到解决方案......
附言显然它确实在最新版本的 TypeScript 中工作。
最佳答案
在您引用的同一页面中,标题为 Indexable Types
的部分对此进行了讨论。
你需要这样做:
function hello(state = {}, action: IReduxAction) {
return { type: action.type, text: action["text"] };
}
因为您的接口(interface)定义被定义为具有从字符串(键)到任何(值)的索引。
关于typescript - 如何声明具有精确字段和任何额外属性的 TypeScript 对象接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37296757/