如何将 ImmutableJS Map 与 TypeScript 结合使用

Mar*_*com 6 dictionary immutability circular-reference typescript

我有一个看起来像这样的树结构:

interface TreeData {
  id : number;
  text : string;
  children : TreeData[];
}
Run Code Online (Sandbox Code Playgroud)

我想将其包装到一个不可变的映射中,但由于我使用的是 TypeScript,所以我希望使用 get 和 set 具有一些类型安全性。我在网上找到了 2 篇文章,了解如何做到这一点的建议,请参阅:

https://github.com/facebook/immutable-js/issues/683 https://blog.mayflower.de/6630-typescript-redux-immutablejs.html

然而我的问题是我的 TreeData 包含 TreeData 子级的列表。如果我这样定义 ImmutableMap:

export interface ImmutableMap<T, K, V> extends Map<K, V> {
  get<I extends keyof T>( key : I & K ) : T[I] & V;
  set<S extends keyof T>( key : S & K, value : T[S] & V ) : Map<K, V>;
}
Run Code Online (Sandbox Code Playgroud)

然后,当我尝试定义以下内容时,我收到一条打字稿错误消息:

type ImmutableTreeData = ImmutableMap<TreeData, string, string | List<ImmutableTreeData>>;
Run Code Online (Sandbox Code Playgroud)

[TS] 类型别名 ImmutableTreeData 循环引用自身

如何修复此 TypeScript 错误?

小智 0

记录一下怎么样?

interface ITreeData {
  id: number;
  text: string;
  chilren?: ITreeData;
}

const defaultTreeData: ITreeData = {
  id: 0,
  text: "",
  chilren: undefined
};

class TreeData extends Record(defaultTreeData) {
  public static Init() {
    return new TreeData(defaultTreeData);
  }
}

const treeData = TreeData.Init().set("text", "ok");

const treeData2 = treeData.set("chilren", treeData);

console.log(treeData2);
Run Code Online (Sandbox Code Playgroud)