Skip to content

assignToObject

reference
1 min readUpdated

Kind: Function

Source: packages/core/repl/assign-to-object.util.ts

Part of: Core

Similar to Object.assign but copying properties descriptors from source as well.

assignToObject copies all own properties from a source object to a target object while preserving each property's descriptor, including getters, setters, enumerability, writability, and configurability. Unlike Object.assign, it does not read property values during copying, making it suitable for REPL and runtime utilities that need to retain object behavior accurately.

Signature

ts
function assignToObject(target: T, source: U): T & U

Parameters

NameType
targetT
sourceU

Returns: T & U

Diagram

mermaid
graph LR
  Source[Source object] --> Keys[Own property keys]
  Keys --> Descriptors[Get property descriptors]
  Descriptors --> Define[Define properties on target]
  Define --> Target[Target object]

Usage

ts
import { assignToObject } from './assign-to-object.util';

const source = {};

Object.defineProperty(source, 'computed', {
  enumerable: true,
  get() {
    return 'generated value';
  },
});

const target = { existing: true };

assignToObject(target, source);

console.log(target.existing); // true
console.log(target.computed); // "generated value"

const descriptor = Object.getOwnPropertyDescriptor(target, 'computed');
console.log(typeof descriptor?.get); // "function"

AI Coding Instructions

  • Use assignToObject when copied properties must retain getters, setters, and descriptor flags; use Object.assign only for plain value copying.
  • Preserve own-property descriptor semantics, including symbol keys if the implementation supports them.
  • Do not access source property values while copying, as doing so can invoke getters and change behavior.
  • Ensure the target object can accept the copied descriptors; non-configurable target properties may cause Object.defineProperty to throw.
  • Keep this utility focused on descriptor-preserving assignment for REPL object composition and runtime inspection flows.

Was this page helpful?

Download as PDF
assignToObject — NestJS head-to-head