Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

safeObjectMerge.ts

38 lines1.1 KB

1function isSafeKey(key: string): boolean {
2 return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'
3}
4​
5/**
6 * Merge target and source into a new null-proto object, filtering dangerous keys.
7 */
8export function safeObjectMerge<T extends Record<string, unknown>>(
9 target: T | undefined,
10 source: Record<string, unknown> | null | undefined,
11): T {
12 const result = Object.create(null) as T
13 if (target) {
14 for (const key of Object.keys(target)) {
15 if (isSafeKey(key)) result[key as keyof T] = target[key] as T[keyof T]
16 }
17 }
18 if (source && typeof source === 'object') {
19 for (const key of Object.keys(source)) {
20 if (isSafeKey(key)) result[key as keyof T] = source[key] as T[keyof T]
21 }
22 }
23 return result
25​
26/**
27 * Create a null-prototype object, optionally copying from source.
28 */
29export function createNullProtoObject<T extends object>(
30 source?: T,
31): { [K in keyof T]: T[K] } {
32 if (!source) return Object.create(null)
33 const obj = Object.create(null)
34 for (const key of Object.keys(source)) {
35 if (isSafeKey(key)) obj[key] = (source as Record<string, unknown>)[key]
36 }
37 return obj