How to use ImmutableJS Map with TypeScript

爱⌒轻易说出口 提交于 2021-01-29 02:53:49

问题


I have a tree structure that looks something like this:

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

I want to wrap this up into an Immutable Map but since I'm using TypeScript, I would like some type safety around using get and set. I found 2 articles online for suggestions on how one might be able to do this, see:

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

However my problem is that my TreeData contains a list of TreeData children. If I define my ImmutableMap this way:

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

Then when I try to define the following, I get a typescript error message:

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

[TS] Type alias ImmutableTreeData circularly references itself

How can I fix this TypeScript error?


回答1:


How about a record?

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

Usage:

const myMap = TypedMap(value);

References:

  • https://stackoverflow.com/a/43609180/779957
  • https://blog.mayflower.de/6630-typescript-redux-immutablejs.html


来源:https://stackoverflow.com/questions/52824312/how-to-use-immutablejs-map-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!