0
# Object Utilities
1
2
Object creation, property checking, and deep copying utilities for safe object manipulation.
3
4
## Capabilities
5
6
### Object Creation
7
8
Create objects with specified prototypes or null prototype.
9
10
```typescript { .api }
11
/**
12
* Create an object with specified prototype (Object.create wrapper)
13
* @param obj - Prototype object or null (default: null)
14
* @returns New object with specified prototype
15
*/
16
function create(obj?: object | null): object;
17
18
/**
19
* Reference to Object.assign for object property copying
20
*/
21
const assign: typeof Object.assign;
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import { create, assign } from "@intlify/shared";
28
29
// Create object with null prototype (no inherited properties)
30
const cleanObject = create();
31
console.log(Object.getPrototypeOf(cleanObject)); // null
32
33
// Create object with specific prototype
34
const prototype = { method() { return "inherited"; } };
35
const derived = create(prototype);
36
console.log(derived.method()); // "inherited"
37
38
// Object assignment
39
const target = { a: 1 };
40
const source = { b: 2, c: 3 };
41
const result = assign(target, source);
42
console.log(result); // { a: 1, b: 2, c: 3 }
43
```
44
45
### Property Checking
46
47
Check if an object has its own property (not inherited).
48
49
```typescript { .api }
50
/**
51
* Check if object has own property (not inherited)
52
* @param obj - Object or array to check
53
* @param key - Property key to check for
54
* @returns True if object has own property with the key
55
*/
56
function hasOwn(obj: object | Array<any>, key: string): boolean;
57
```
58
59
**Usage Example:**
60
61
```typescript
62
import { hasOwn } from "@intlify/shared";
63
64
const obj = { name: "Alice", age: 30 };
65
const arr = ["a", "b", "c"];
66
67
console.log(hasOwn(obj, "name")); // true
68
console.log(hasOwn(obj, "toString")); // false (inherited)
69
console.log(hasOwn(arr, "0")); // true (array index)
70
console.log(hasOwn(arr, "length")); // true (own property)
71
console.log(hasOwn(arr, "push")); // false (inherited method)
72
73
// Safe property access
74
function getProperty(obj: any, key: string) {
75
if (hasOwn(obj, key)) {
76
return obj[key];
77
}
78
return undefined;
79
}
80
```
81
82
### Deep Copying
83
84
Deep copy properties from source object to destination object.
85
86
```typescript { .api }
87
/**
88
* Deep copy properties from source to destination object
89
* @param src - Source object to copy from
90
* @param des - Destination object to copy to
91
* @throws Error if src or des are not objects or are arrays
92
*/
93
function deepCopy(src: any, des: any): void;
94
```
95
96
**Usage Examples:**
97
98
```typescript
99
import { deepCopy } from "@intlify/shared";
100
101
// Basic deep copying
102
const source = {
103
name: "Alice",
104
details: {
105
age: 30,
106
address: {
107
city: "New York",
108
country: "USA"
109
}
110
},
111
hobbies: ["reading", "swimming"]
112
};
113
114
const destination = {};
115
deepCopy(source, destination);
116
117
console.log(destination);
118
// Deep copy complete - nested objects and arrays are copied
119
120
// Modifying source doesn't affect destination
121
source.details.age = 31;
122
source.hobbies.push("cooking");
123
console.log(destination.details.age); // Still 30
124
console.log(destination.hobbies); // Still ["reading", "swimming"]
125
```
126
127
**Advanced Usage:**
128
129
```typescript
130
import { deepCopy, create } from "@intlify/shared";
131
132
// Merge configuration objects
133
function mergeConfig(defaultConfig: any, userConfig: any) {
134
const result = create();
135
deepCopy(defaultConfig, result);
136
deepCopy(userConfig, result);
137
return result;
138
}
139
140
const defaultConfig = {
141
theme: "light",
142
features: {
143
notifications: true,
144
analytics: false
145
}
146
};
147
148
const userConfig = {
149
theme: "dark",
150
features: {
151
analytics: true
152
}
153
};
154
155
const finalConfig = mergeConfig(defaultConfig, userConfig);
156
console.log(finalConfig);
157
// {
158
// theme: "dark",
159
// features: {
160
// notifications: true,
161
// analytics: true
162
// }
163
// }
164
```
165
166
### Type Conversion Utilities
167
168
Additional utilities for object type handling.
169
170
```typescript { .api }
171
/**
172
* Reference to Object.prototype.toString for type checking
173
*/
174
const objectToString: () => string;
175
176
/**
177
* Get type string representation of a value
178
* @param value - Value to get type string for
179
* @returns Type string like '[object Object]', '[object Array]'
180
*/
181
function toTypeString(value: unknown): string;
182
```
183
184
**Usage Example:**
185
186
```typescript
187
import { toTypeString, objectToString } from "@intlify/shared";
188
189
console.log(toTypeString({})); // "[object Object]"
190
console.log(toTypeString([])); // "[object Array]"
191
console.log(toTypeString(new Date())); // "[object Date]"
192
console.log(toTypeString(/regex/)); // "[object RegExp]"
193
194
// Use objectToString directly
195
console.log(objectToString.call(null)); // "[object Null]"
196
console.log(objectToString.call(undefined)); // "[object Undefined]"
197
```
198
199
## Deep Copy Behavior
200
201
### Supported Operations
202
203
The `deepCopy` function handles:
204
- **Primitive values**: Directly assigned
205
- **Objects**: Recursively copied (excluding prototype chain)
206
- **Arrays**: Converted to new arrays with copied elements
207
- **Nested structures**: Full deep traversal
208
209
### Security Features
210
211
- **Prototype pollution protection**: Skips `__proto__` property
212
- **Type validation**: Ensures source and destination are objects
213
- **Array handling**: Properly converts between arrays and objects
214
215
### Limitations
216
217
```typescript
218
import { deepCopy } from "@intlify/shared";
219
220
// ❌ These will throw errors
221
try {
222
deepCopy(null, {}); // Error: src is not an object
223
deepCopy({}, []); // Error: des is an array
224
deepCopy([], {}); // Error: src is an array
225
} catch (error) {
226
console.error("deepCopy error:", error.message);
227
}
228
229
// ✅ Correct usage
230
const src = { a: 1, b: { c: 2 } };
231
const dest = {};
232
deepCopy(src, dest); // Works correctly
233
```
234
235
### Stack-based Implementation
236
237
The function uses an iterative approach with a stack to handle deep nesting without recursion limits:
238
239
```typescript
240
// Conceptual implementation
241
function deepCopy(src: any, des: any): void {
242
const stack = [{ src, des }];
243
244
while (stack.length) {
245
const { src, des } = stack.pop()!;
246
247
Object.keys(src).forEach(key => {
248
if (key === '__proto__') return; // Security: skip prototype pollution
249
250
// Handle nested objects and arrays
251
if (isObject(src[key])) {
252
if (!isObject(des[key])) {
253
des[key] = Array.isArray(src[key]) ? [] : create();
254
}
255
stack.push({ src: src[key], des: des[key] });
256
} else {
257
des[key] = src[key]; // Copy primitive values
258
}
259
});
260
}
261
}
262
```