Typescript如何声明子类类型? [英] Typescript How to declare a subclass type?

查看:695
本文介绍了Typescript如何声明子类类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能有这样的东西?

Is it possible to have something like this?

export abstract class FilterBoxElement {
    abstract getEntities: any;
}
export interface FilterBoxControlSuggestions extends FilterBoxElement {
    getEntities: // some implementation with different parameters
}
export interface FilterBoxControlDropDown extends FilterBoxElement {
    getEntities: // some implementation with different parameters
}

export interface FilterBoxDataProps {
    controlElement: FilterBoxElement // FilterBoxControlSuggestions or FilterBoxControlDropDown 
}

我希望 controlElement 必须是 FilterBoxControlSuggestions FilterBoxControlDropDown 。但是现在我可以把所有东西放进去。有没有办法实现这个目标?

I want that controlElement has to be a FilterBoxControlSuggestions or a FilterBoxControlDropDown. But right now I can put everything in it. Is there a way to achieve this?

推荐答案

您可以使用联合类型:

export interface FilterBoxDataProps {
    controlElement: FilterBoxControlSuggestions | FilterBoxControlDropDown 
}

或者如果你想要全部使用泛型FilterBoxElement的子类:

Or with generics if you want all subclasses of FilterBoxElement:

export interface FilterBoxDataProps<T extends FilterBoxElement> {
    controlElement: T
}

这篇关于Typescript如何声明子类类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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