How to safely enter an object font in TypeScript to update an immutable object

Object distribution is widely used to update an old object in a functional style, for example:

let o1 = { x: 5, y: 6 };
let o2 = { ...o1, y: 10 };
alert(JSON.stringify(o2));

The new TypeScript 2.1 now implements an object extension, but unlike a simple object literal, it allows you to have unknown properties:

interface Point { x: number, y: number }

let o1: Point = { x: 5, y: 6 };

//ERROR: Object literal may only specify known properties
let o2: Point = { x: 5, y: 6, z: 10 };

// OK: had I wanted to update y, but misspeled it,  
// I would get new "z" prop instead of compiler error which I would prefer to have:
let o3: Point = { ...o1, z: 10 }; 

alert(JSON.stringify(o3));

So here is the question: how to safely use a distribution object in TypeScript to update an object? Or a more general question: how to update an object in a functional (immutable) and safe form in TypeScript 2.1?

+4
source share
1 answer

. Object.assign. JS.

, ( ), Object spread .

, - :

function update<T, K extends keyof T>(obj: T, updateSpec: Pick<T, K>): T {
  const result = {} as T
  Object.keys(obj).forEach(key => result[key] = obj[key])
  Object.keys(updateSpec).forEach((key: K) => result[key] = updateSpec[key])
  return result
}

, , .

+6

Source: https://habr.com/ru/post/1663817/


All Articles