【问题标题】:Can I use object spread syntax in angular + ngrx?我可以在 angular + ngrx 中使用对象扩展语法吗?
【发布时间】:2017-08-30 16:49:10
【问题描述】:

我从here 阅读了有关对象传播语法的信息,我正在尝试在我的项目中使用它,我的设置如下:

  • 角2
  • 角度/cli 1.0.0-rc.0
  • ngrx/核心 1.2.0
  • ngrx/存储 2.2.1
  • rxjs 5.1.0
  • 打字稿 2.0.10

在我的 reducer.ts 中有

export interface State {
  [id: number]: string
}

export function reducer(state= {}, action: Action): State {
case 'TEST':
  return {
    ...state,
    2: 'foo'
  }
}

但是我得到了以下编译错误,我正在尝试找出问题所在:

Property assignment expected
Type '{ 2: string; state: State; }' is not assignable to type 'State'
Object literal may only specify known properties, and 'state' does not exist in type 'State'

有什么想法吗?谢谢!

【问题讨论】:

    标签: javascript object redux ngrx spread-syntax


    【解决方案1】:

    不适用于您使用的 TypeScript 版本。

    对对象属性传播语法的支持是introduced in TypeScript 2.1:

    对象传播和休息

    TypeScript 2.1 带来了对 ES2017 Spread and Rest 的支持。

    类似于数组传播,传播对象可以很方便地获得浅拷贝:

    let copy = { ...original };
    

    【讨论】:

    • 太棒了!非常感谢!
    • 一般来说,我可以在 Angular 项目中将 typescript 版本更新为最新版本吗?或者特定版本的角度是否需要特定版本的打字稿?
    • 我不记得最近的 TypeScript 版本有什么特别的问题。我通常使大多数东西尽可能保持最新,所以我已经有一段时间没有使用你在问题中提到的版本了。发生了重大更改,但它们已在我的代码中。
    • 这里有一个关于版本、特性和变化的综合文档:github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript
    猜你喜欢
    • 1970-01-01
    • 2017-01-30
    • 2021-11-22
    • 2011-07-30
    • 1970-01-01
    • 2011-11-21
    • 2021-12-25
    • 2011-09-05
    • 2021-12-23
    相关资源
    最近更新 更多