The source type.
// Safely copy properties from an untrusted source
function safeMerge<T extends object>(target: T, source: any): T {
forEachOwnKeySafe(source, (key, value) => {
(target as any)[key] = value;
});
return target;
}
// Note: use Object.defineProperty so "__proto__" is a real own enumerable
// property rather than being treated as prototype syntax by the JS engine.
const src: any = { name: "Alice" };
Object.defineProperty(src, "__proto__", { value: "attack", enumerable: true, configurable: true, writable: true });
const result = safeMerge({}, src);
// result.name === "Alice" (__proto__ was silently skipped)
// Symbol keys are included but unsafe string keys are filtered
const sym = Symbol("safe");
// Note: use Object.defineProperty so "__proto__" is a real own enumerable
// property rather than being treated as prototype syntax by the JS engine.
const obj: any = { a: 1, [sym]: "ok" };
Object.defineProperty(obj, "__proto__", { value: "bad", enumerable: true, configurable: true, writable: true });
forEachOwnKeySafe(obj, (key, value) => {
console.log(String(key), value);
// "a" 1
// "Symbol(safe)" "ok"
// "__proto__" is never visited
});
Calls the provided
callbackFnonce for each own enumerable key (string and symbol) in the supplied value, skipping keys that are considered unsafe (__proto__,constructor,prototype). The callback can stop iteration early by returning-1.This helper wraps forEachOwnKey with extra key filtering for safer assignment flows. Use this instead of forEachOwnKey whenever keys come from untrusted input (e.g. user-supplied objects, parsed JSON).