允许其他属性的 TypeScript 接口 [英] TypeScript interface that allows other properties

查看:33
本文介绍了允许其他属性的 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: {}
        })
    }
}

给出编译错误,因为 someOtherDataActionPayload 接口不匹配.问题是许多不同的动作"类将重用相同的调度程序,因此虽然它是 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 
}

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

这篇关于允许其他属性的 TypeScript 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆