Home > Net >  Enum of types in TypeScript
Enum of types in TypeScript

Time:09-22

I am currently in the process of converting a project to TypeScript. I have this Algorithm object which contains a getRun function and an edgesRepresentation string which contains information about how the edges are represented ("adjacencyList" | "adjacencyMatrix" | "edgeList", though only "adjacencyList" is being used now). I do not want to make the IAlgorithm interface a generic for the edgesRepresentation if possible (as I see no reason for the Algorithm to be a generic just because its run function is one too) so I'm preferably looking for a more dynamic solution. The problem is, when IAlgorithm has a getRun function that returns a run function, the run function (which I have no problem making a generic) needs to have assumptions about the way edges are represented, but those are different for different edgesRepresentation objects. I want to have something similar to this:

interface IAlgorithm {
    getRun: (arg0: {considers: Considers, setIsDone: (arg0?: boolean)=>void}) => IRunType;
}

export interface IRunType<T extends EdgesRepresentationType> {
    (nodesIds: List<string>, edgeList: T):void;
}

type AdjacencyListType = Map<string, Map<string, typeof EdgeRecord>>;

export enum EdgesRepresentationType {
    adjacencyList=AdjacencyListType
}

Here EdgeRecord is just an immutable Record containing information about an edge.

Something like that would be good as well:

interface IAlgorithm<T extends EdgesRepresentationType> {
    getRun: (arg0: {considers: Considers, setIsDone: (arg0?: boolean)=>void}) => IRunType<T>;
}

export type ITopSort = IAlgorithm<EdgesRepresentationType.adjacencyList>;

export interface IRunType<T extends EdgesRepresentationType> {
    (nodesIds: List<string>, edgeList: T):void;
}

type AdjacencyListType = Map<string, Map<string, typeof EdgeRecord>>;

export enum EdgesRepresentationType {
    adjacencyList=AdjacencyListType
}

I just cannot find a way for this to work, although my TypeScript knowledge is fairly limited.

CodePudding user response:

I hope I understand your problem correctly, but yes, then why not using type union, like so:

type AdjacencyListType = Map<string, Map<string, typeof EdgeRecord>>;
export type EdgesRepresentationType = AdjacencyListType | AdjacencyMatrix | EdgeList;

I'm aware this will make the IAlgorithm kind of generic, but narrowed down to some of types only, but at some point you will have to if or switch between types passed to it's function even when using enum-like solution.
Speaking of which: I don't think that enum of types explicitly is a possible solution, as anything regarding the custom type will most likely be a computed type.

  • Related