【问题标题】:Immutable.js and TypescriptImmutable.js 和 Typescript
【发布时间】:2015-12-16 07:33:52
【问题描述】:

我正在使用 react-redux 创建一个应用程序。在那我使用打字稿和immutable.js。当我对类型化对象使用诸如 updateIn() 之类的不可变方法时,它会抛出错误。

以下是我尝试过的代码:

interface aType{
  id: number
}

function randFun(a:aType){
  a = a.updateIn([....]); //It is throwing error in this line of code.
}
randFun({id:2});

类型 {...} 中不存在属性“updateIn”

我怎样才能摆脱这个错误???

【问题讨论】:

  • 如果你打算使用不可变的js,你必须放弃为你的不可变对象使用接口,所以你必须在不可变的定义文件中将aType接口替换为Map接口
  • 您还可以查看github.com/engineforce/ImmutableAssign,这是一个支持 TypeScript 类型检查的轻量级不可变助手,并允许您继续使用 POJO(普通旧 JavaScript 对象)。

标签: typescript immutable.js


【解决方案1】:

对于 TypeScript,这是因为 updateIn 没有在 aType 接口中定义。要修复它,您可以编写:

interface aType{
  id: number,
  updateIn(n: number): aType
}

function randFun(a:aType){
  let n = 5;    
  a = a.updateIn(n); // No error here
}
randFun({id:2}); // This still need to be fixed!

但是,它也不能在 JavaScript 中工作,因为你不能在 {id:2} 对象上调用 updateIn

【讨论】:

猜你喜欢
  • 2021-07-01
  • 1970-01-01
  • 2017-11-25
  • 2018-07-06
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
相关资源
最近更新 更多