Can I use object spread syntax in angular + ngrx?

2019-07-24 05:40发布

问题:

I was reading from here about the object spread syntax and I'm trying to use it in my project, my setup is the following:

  • angular 2
  • angular/cli 1.0.0-rc.0
  • ngrx/core 1.2.0
  • ngrx/store 2.2.1
  • rxjs 5.1.0
  • typescript 2.0.10

In my reducer.ts I have

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

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

But I got the following compiling error, I'm trying to figure out what's wrong:

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'

Any ideas? Thanks!

回答1:

Not with the version of TypeScript that you are using.

Support for the object properties spread syntax was introduced in TypeScript 2.1:

Object Spread and Rest

TypeScript 2.1 brings support for ES2017 Spread and Rest.

Similar to array spread, spreading an object can be handy to get a shallow copy:

let copy = { ...original };