Typescript如何声明子类类型?

时间:2017-01-12 11:12:47

标签: javascript reactjs typescript

有可能有这样的东西吗?

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必须是FilterBoxControlSuggestionsFilterBoxControlDropDown。但是现在我可以把所有东西放进去。有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:5)

您可以使用联合类型:

export interface FilterBoxDataProps {
    controlElement: FilterBoxControlSuggestions | FilterBoxControlDropDown 
}

如果你想要所有FilterBoxElement的子类:

,或者使用泛型
export interface FilterBoxDataProps<T extends FilterBoxElement> {
    controlElement: T
}

答案 1 :(得分:3)

如果它可以是一种类型或另一种类型,请使用联合类型(|):

export interface FilterBoxDataProps {
    controlElement: FilterBoxControlSuggestions | FilterBoxControlDropDown;
}