[英]Strongly typed Immutable.js Records in TypeScript
I'm unable to find a good resource for this question. 我找不到这个问题的好资源。 Essentially I want to describe types for my data using an interface in TypeScript, but my data is Immutable.js records which appears to complicate matters, please see my example below.
本质上,我想使用TypeScript中的接口来描述数据的类型,但是我的数据是Immutable.js记录,这似乎使事情变得复杂,请参见下面的示例。
interface tree extends Immutable.Map<string, any> {
readonly id: number,
readonly type: number
}
let trees = Immutable.List<tree[]>([
Map<tree>({
id: 101,
type: 1
}),
Map<tree>({
id: 201,
type: 3
})
])
Questions with the above: 上面的问题:
<tree[]>
when creating the list? <tree[]>
简单声明吗? And then any Map added to the list be type checked against this? I've been working on this for days and I simply can't get it to work, it should be this simple according to everything I've read. 我已经为此工作了好几天,但我根本无法使它起作用,根据我所读的所有内容,它应该是如此简单。
Any help would be greatly appreciated. 任何帮助将不胜感激。
You are creating a List
of arrays
of trees
, which is an extended Map
. 您正在创建
trees
arrays
List
,这是扩展的Map
。 This is what it should look like: 它应该是这样的:
let trees = Immutable.List<tree[]>(
[ // List
[ // Array
<tree>Immutable.Map<any>({
id: 101,
type: 1
}),
<tree>Immutable.Map<any>({
id: 201,
type: 3
})
]
]
);
Answering your questions: 回答您的问题:
Map
that builds a map from an object. Map
方法,该方法从对象构建地图。 I added the <tree>
cast because it is an array of trees
, not maps. <tree>
强制转换,因为它是一排trees
而不是地图。 You are trying something like: 您正在尝试类似:
var singleTree: tree = Immutable.Map<tree>( { id: 101, type: 1 } );
But your tree is a map of the any
type. 但是您的树是
any
类型的地图。 So, this is the right syntax: 因此,这是正确的语法:
let singleTree: tree = <tree>Immutable.Map<any>( { id: 101, type: 1 } );
For the code above, we can simplify and force a type check if we create a tree
function to wrap the Map
function, so, the final solution would be: 对于上面的代码,如果我们创建
tree
函数来包装Map
函数,则可以简化并强制进行类型检查,因此最终的解决方案是:
function tree(obj: { [key: string]: any, id: number, type: number }): tree {
return <tree>Immutable.Map<any>(obj);
}
let trees = Immutable.List<tree[]>(
[ // List
[ // Array
tree({
id: 101,
type: 1
}),
tree({
id: 201,
type: 3
})
]
]
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.