如何在TypeScript中使用ImmutableJS Map [英] How to use ImmutableJS Map with TypeScript
问题描述
我有一个看起来像这样的树结构:
I have a tree structure that looks something like this:
interface TreeData {
id : number;
text : string;
children : TreeData[];
}
我想将其包装成一个不可变的映射,但是由于我使用的是TypeScript,所以我希望在使用get和set时有一些类型安全性.我在网上找到2篇文章,以寻求有关如何做到这一点的建议,请参阅:
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
但是我的问题是我的TreeData包含TreeData子级列表.如果我以这种方式定义我的ImmutableMap:
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]类型别名ImmutableTreeData循环引用自身
[TS] Type alias ImmutableTreeData circularly references itself
如何解决此TypeScript错误?
How can I fix this TypeScript error?
推荐答案
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);
参考文献:
- https://stackoverflow.com/a/43609180/779957
- https://blog.mayflower.de/6630-typescript-redux-immutablejs.html
这篇关于如何在TypeScript中使用ImmutableJS Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!