moderndash icon indicating copy to clipboard operation
moderndash copied to clipboard

Non-constructing `object.set`

Open Dimava opened this issue 2 years ago • 0 comments

In Typescript, in may be preferred to set properties that are already defined in interface rather then adding new properties

So it a variant of set that can't create properties not defined in the interface in may come useful

The sefSafe function may either return the input type, or return the input type with removed oprionals ? on created path.

See https://stackoverflow.com/questions/76255065/typescript-type-safe-version-of-lodashs-set/76280420#1

example usage:

type Pos = { x: number, y: number };
const pos0 = {} as DeepPartial<Pos>;
const pos1 = setSafe(pos0, 'x', 1); // { x: number, y?: number }
const pos2 = setSafe(pos1, 'y', 2); // { x: number, y: number }
const pos3: Pos = pos2;

Dimava avatar May 18 '23 11:05 Dimava