Typescript 如何声明子类类型?

IT技术 javascript reactjs typescript
2021-05-09 16:49:08

有可能有这样的东西吗?

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

2个回答

你可以用联合类型来做到这一点:

export interface FilterBoxDataProps {
    controlElement: FilterBoxControlSuggestions | FilterBoxControlDropDown 
}

或者如果您想要 FilterBoxElement 的所有子类,则使用泛型:

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

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

export interface FilterBoxDataProps {
    controlElement: FilterBoxControlSuggestions | FilterBoxControlDropDown;
}