我无法找到解决这个问题的好资源。本质上,我想使用 TypeScript 中的接口(interface)来描述数据的类型,但我的数据是 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
})
])
以上问题:
- 为什么我必须重复列表中每张 map 的类型?该类型不应该简单地由
<tree[]>
声明吗?创建列表时?然后添加到列表中的任何 map 都会根据此进行类型检查吗? - 目前此示例错误,指出“属性“id”与索引签名不兼容。类型“number”不可分配给类型“tree”。这是有道理的!但是,阅读文档后,我无法工作如何让它工作?阅读文档,它指出我需要一个 ID,但我想要一个 map 数组,如果我没记错的话,在这种情况下我的签名只是标准数组 ID?
我已经为此工作了好几天,但我就是无法让它工作,根据我读过的所有内容,它应该这么简单。
任何帮助将不胜感激。
最佳答案
您正在创建 List
的arrays
的trees
,这是一个扩展 Map
。它应该是这样的:
let trees = Immutable.List<tree[]>(
[ // List
[ // Array
<tree>Immutable.Map<any>({
id: 101,
type: 1
}),
<tree>Immutable.Map<any>({
id: 201,
type: 3
})
]
]
);
回答您的问题:
- 您不会重复每张 map 的类型。实际上,你正在调用一个方法
Map
从对象构建 map 。我添加了<tree>
因为它是trees
的数组,而不是 map 。 您正在尝试以下操作:
var singleTree: tree = Immutable.Map<tree>( { id: 101, type: 1 } );
但是你的树是
any
的 map 类型。所以,这是正确的语法:let singleTree: tree = <tree>Immutable.Map<any>( { id: 101, type: 1 } );
对于上面的代码,如果我们创建 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
})
]
]
);
关于javascript - TypeScript 中的强类型 Immutable.js 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44687489/