Creating actions

An action should modify the state. To do that, we will first create three helper functions. One to modify a part of an object, one to modify a part of an array, and one to easily create a new array.

We use the same update function as we did in Chapter 3, Note-Taking App with a Server. We add this function to lib/model/utils.ts.

export function update<U extends V, V>(old: U, changes: V): U { 
  const result = Object.create(Object.getPrototypeOf(old)); 
  for (const key of Object.keys(old)) { 
    result[key] = (<any> old)[key]; 
  } 
  for (const key of Object.keys(changes)) { 
    result[key] = (<any> changes)[key]; 
  } 
  return result; 
} 

We also create a function that changes the element at a certain index of an array. The other elements will remain at ...

Get TypeScript: Modern JavaScript Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.