typescript - 如何声明具有精确字段和任何额外属性的 TypeScript 对象接口(interface)

标签 typescript

我在声明 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/

相关文章:

angular - 如何在 Angular 7 中使用 typescript 获取属性值

typescript - deno 捆绑失败。类型 'getIterator' 上不存在属性 'ReadableStream<R>'

debugging - 无法在 VSCode 中调试 Typescript

angular - 在 Angular2 中将 jquery-steps 与 FormGroup 结合使用

Angular 4+ 服务引用了另一个服务良好实践

基于字符串参数的 typescript 条件返回类型

reactjs - React Storybook 在 args 中传递函数

Angular 将一个组件作为另一个组件的 ng-template 传递

typescript - 扩展 TestController/TestControllerPromise

ios - 在 ios 上使用 typescript/web 音频 api