Skip to content

Commit e6c18aa

Browse files
committed
add function to objectify input
1 parent 62d8bf2 commit e6c18aa

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

packages/utils/src/object.ts

+19
Original file line numberDiff line numberDiff line change
@@ -398,3 +398,22 @@ export function dropUndefinedKeys<T>(val: T): T {
398398

399399
return val;
400400
}
401+
402+
/**
403+
* Ensure that something is an object.
404+
*
405+
* Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper
406+
* classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.
407+
*
408+
* @param wat The subject of the objectification
409+
* @returns A version of "wat` which can safely be used with `Object` class methods
410+
*/
411+
export function objectify(wat: unknown): typeof Object {
412+
return typeof wat === undefined || typeof wat === null
413+
? new String(wat)
414+
: isPrimitive(wat)
415+
? // dummy comment necessary for prettier not to break the @ts-ignore
416+
// @ts-ignore TS reads the constructor as a plain function rather than something "constructible"
417+
new wat.constructor(wat)
418+
: wat;
419+
}

0 commit comments

Comments
 (0)