Crocsx
Crocsx

Reputation: 7589

Create a Generic type interface with some specific interface

I don't really know the terms to search on google for this, so it might be duplicated.

I have an interface that looks like

export interface SolidOptions<T>  {
  position: Cartesian3;
  options?: T;
}

now, I want this T to be ONLY of 3 types : CylinderOptions | RectangleOptions | PolygoneOptions

I do NOT want this solution :

export interface SolidOptions<T>  {
  position: Cesium.Cartesian3;
  options?: CylinderOptions | RectangleOptions | PolygoneOptions;
}

the reason why is I want to use this as follow :

    static generateCylinder = (options: SolidOptions<CylinderOptions>)=>  {
    }
    
    static generateRectangle = (options: SolidOptions<RectangleOptions >)=>  {
    }

    static generatePolygon = (options: SolidOptions<PolygoneOptions>)=>  {
    }

and not having the abilities to pass the wrong type to the wrong function.

Upvotes: 0

Views: 21

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

You can define constraint on generic type parameter:

export interface SolidOptions<T extends CylinderOptions | RectangleOptions | PolygoneOptions> {
  position: Cartesian3;
  options?: T;
}

Upvotes: 3

Related Questions