Search code examples
typescriptgenericstypescastingtype-conversion

Parameter of any type that extends another type in TypeScript?


I'm creating an HTML5 game with TypeScript, and I want to render all children of a GameObject automatically. But there are many different classes that can extend GameObject class. What I ideally want is something like below, where the type of the object in the array can be any type that extends GameObject class. Also, I'd like to refrain from type casting and generics, as well as specifying all the available types as union types.

protected children: Array<any extends GameObject> = [];

Is this possible in some way or should I try to do it using other ways?


Solution

  • The following:

    protected children: Array<GameObject> = [];
    

    Will automatically accept anything that extends GameObject 🌹

    More

    See type compatibility

    Additional Tip

    Conventionally TypeScript people write GameObject[] instead of Array<GameObject> ❤️