【问题标题】:Enum of types in TypeScriptTypeScript 中的类型枚举
【发布时间】:2022-09-23 03:51:53
【问题描述】:

我目前正在将项目转换为 TypeScript。我有这个 Algorithm 对象,它包含一个 getRun 函数和一个 edgesRepresentation 字符串,其中包含有关如何表示边缘的信息(\"adjacencyList\" | \"adjacencyMatrix\" | \"edgeList\",尽管现在只使用\"adjacencyList\")。如果可能的话,我不想让 IAlgorithm 接口成为 edgesRepresentation 的通用接口(因为我认为没有理由仅仅因为它的 run 函数也是一个通用的算法)所以我最好寻找一个更动态的解决方案.问题是,当 IAlgorithm 有一个返回 run 函数的 getRun 函数时,run 函数(我对它进行泛型没有问题)需要对边的表示方式进行假设,但对于不同的 edgesRepresentation 对象,这些假设是不同的。我想要类似的东西:

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
}

这里的 EdgeRecord 只是一个包含边信息的不可变记录。

像这样的东西也很好:

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
}

尽管我的 TypeScript 知识相当有限,但我只是找不到解决方法。

  • 你展示了两件你想要的东西,而不是你拥有的东西或这两者有什么问题。你能解释一下缺少什么吗?

标签: javascript typescript


【解决方案1】:

我希望我能正确理解您的问题,但如果是,那么为什么不使用type union,如下所示:

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

我知道这将使IAlgorithm 成为通用类型,但仅限于某些类型,但在某些时候你将要即使使用类似枚举的解决方案,也必须在传递给它的函数的类型之间使用ifswitch
说到这里: 我不认为明确地枚举类型是一个可能的解决方案,因为任何关于自定义类型的东西很可能是计算类型。

【讨论】:

  • 谢谢,这正是我想要的。没有意识到这是该语言的一个特性,研究它并没有帮助!
猜你喜欢
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 2018-10-13
  • 2019-12-30
  • 2018-10-31
  • 2020-12-30
  • 1970-01-01
相关资源
最近更新 更多