【问题标题】:How to use ImmutableJS Map with TypeScript如何将 ImmutableJS 映射与 TypeScript 一起使用
【发布时间】:2018-10-15 20:28:03
【问题描述】:

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

interface TreeData {
  id : number;
  text : string;
  children : TreeData[];
}

我想将它封装到一个不可变映射中,但由于我使用的是 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>;
}

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

type ImmutableTreeData = ImmutableMap<TreeData, string, string | List<ImmutableTreeData>>;

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

如何解决这个 TypeScript 错误?

【问题讨论】:

标签: typescript dictionary immutability circular-reference


【解决方案1】:

唱片怎么样?

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);

【讨论】:

【解决方案2】:
import { Map } from "immutable";

export interface ITypedMap<T> extends Map<string, any> {
  get<K extends keyof T>(name: K): T[K];
}

export function TypedMap<T>(value: T): ITypedMap<T> {
  return Map(value) as ITypedMap<T>;
}

用法:

const myMap = TypedMap(value);

参考资料:

【讨论】:

  • 我把它用于一个简单的小案例,但它不适用于.get之外的任何功能。那里一定有更好的解决方案,但我找不到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多