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

Val*_*sin 5 typescript

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

根据手册中的 TypeScript 接口页面(请参阅“多余的属性检查”),我可以这样做:

interface IReduxAction {
  type: string;
  [propName: string]: any;
}
Run Code Online (Sandbox Code Playgroud)

似乎它在某些情况下有效(例如声明变量)

const action: IReduxAction = {
  type: 'hello',
  value: 'world'
};
Run Code Online (Sandbox Code Playgroud)

但是,如果我试图声明使用该操作的函数:

function hello(state = {}, action: IReduxAction) {
  return { type: action.type, text: action.text };
}
Run Code Online (Sandbox Code Playgroud)

它失败,并显示消息“ text类型上不存在属性IReduxAction”。

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

TypeScript操场上的现场示例在这里

PS我检查了“类似”问题,例如为什么会出现错误“对象文字只能指定已知属性”?,但尚未在此处找到解决方案...

PSS显然,它确实可以在最新版本的TypeScript中使用。

Nit*_*mer 2

在您引用的同一页面中,它在标题为 的部分中讨论了它Indexable Types

你需要这样做:

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

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