如何声明具有确切字段和任何其他属性的TypeScript对象接口

我对Redux Action Type的声明有一些问题.根据定义,Redux Action应该具有type属性,并且可以具有一些其他属性.

根据TypeScript interfaces page in HandBook(参见“Excess Property Checks”),我可以这样做:

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类型上不存在属性文本”.

我究竟做错了什么?如何声明一般动作类型?

TypeScript playground上的实例是here

附:我查了“类似”的问题,比如Why am I getting an error “Object literal may only specify known properties”?,并没有在那里找到解决方案……

P.S.S.显然它可以在最新版本的TypeScript中运行.

最佳答案 在同一页面中,您引用它在标题为可索引类型的部分中讨论它.

你需要这样做:

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

因为您的接口定义被定义为具有从字符串(键)到任何(值)的索引.

点赞