允许其他属性的 TypeScript 接口

编程入门 行业动态 更新时间:2024-10-26 00:24:19
本文介绍了允许其他属性的 TypeScript 接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

总而言之,是否可以有一个接口声明一些基本属性,但不限制其他属性?这是我目前的情况:

In summary, is it possible to have an interface that declares some base properties, but does not restrict additional properties? This is my current situation:

我正在使用 Flux 模式,它定义了一个通用的调度程序:

I'm using the Flux pattern, which defines a generic dispatcher:

class Dispatcher<TPayload> { dispatch(arg:TPayload):void { } }

然后我使用我自己的负载类型创建一个调度程序,如下所示:

I then create a dispatcher with my own payload type, like this:

interface ActionPayload { actionType: string } const dispatcher = new Dispatcher<ActionPayload>();

现在我有一些动作代码应该发送带有一些附加数据的有效负载,但是 ActionPayload 接口只允许 actionType.换句话说,这段代码:

Now I have some action code that should dispatch a payload with some additional data, but the ActionPayload interface only allows for actionType. In other words, this code:

interface SomePayload extends ActionPayload { someOtherData: any } class SomeActions { doSomething():void { dispatcher.dispatch({ actionType: "hello", someOtherData: {} }) } }

给出编译错误,因为 someOtherData 与 ActionPayload 接口不匹配.问题是许多不同的动作"类将重用相同的调度程序,因此虽然它是 someOtherData 在这里,但它可能是 anotherKindOfData 那里,等等.目前,我所能做的就是使用 new Dispatcher() 因为将分派不同的动作.不过,所有操作都共享一个基本的 ActionPayload,所以我希望能够限制类型,例如 new Dispatcher() 之类的.这样的事情可能吗?

Gives a compile-error because someOtherData does not match the ActionPayload interface. The issue is that many different "action" classes will re-use the same dispatcher, so while it's someOtherData here it might be anotherKindOfData over there, and so on. At the moment, all I can do to accomodate this is use new Dispatcher<any>() because different actions will be dispatched. All actions share a base ActionPayload, though, so I was hoping to be able to constrain the type like new Dispatcher<extends ActionPayload>() or something. Is something like that possible?

推荐答案

如果您希望 ActionPayload 接受任何其他属性,您可以添加索引器:

If you want ActionPayload to accept any other property you can add an indexer:

interface ActionPayload { actionType: string, [x: string]: any }

参见 github/Microsoft/TypeScript/wiki/Breaking-Changes#strict-object-literal-assignment-checking

更多推荐

允许其他属性的 TypeScript 接口

本文发布于:2023-06-12 05:13:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/651966.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   接口   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!