Typescript How to declare a subclass type?

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 
}

I want to controlElementbe FilterBoxControlSuggestionsor FilterBoxControlDropDown. But now I can put everything in it. Is there any way to achieve this?

+4
source share
2 answers

You can do this using a union type:

export interface FilterBoxDataProps {
    controlElement: FilterBoxControlSuggestions | FilterBoxControlDropDown 
}

Or using generics if you want all subclasses of FilterBoxElement:

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

If it can be one type or another, use the union type ( |):

export interface FilterBoxDataProps {
    controlElement: FilterBoxControlSuggestions | FilterBoxControlDropDown;
}
+3
source

Source: https://habr.com/ru/post/1666595/


All Articles