Function: safeStringify()
safeStringify(
value
:unknown
):string
Defined in: shared/utils/stringConversion.ts:56
Safely converts any value to a string, handling all JavaScript types with meaningful and predictable output.
Parametersโ
valueโ
unknown
The value to convert to a string. Can be any JavaScript type.
Returnsโ
string
The string representation of the input value.
Remarksโ
This function provides comprehensive string conversion logic:
- Returns an empty string for
null
orundefined
. - Returns the value as-is if it is already a string.
- Converts numbers and booleans using
String()
. - For objects, attempts to use safeJsonStringifyWithFallback for serialization. If serialization fails (e.g., circular references), returns a descriptive placeholder.
- For functions, returns the string
"[Function]"
. - For symbols, returns the result of
Symbol.prototype.toString()
. - For all other types, returns
"[Unknown Type]"
.
This approach guarantees that the result is always a string and never the ambiguous '[object Object]'. It is suitable for logging, UI display, and database storage where type safety and clarity are required.
Exampleโ
safeStringify(null); // "null"
safeStringify("hello"); // "hello"
safeStringify(42); // "42"
safeStringify({ a: 1 }); // '{"a":1}'
safeStringify(() => {}); // "[Function]"
safeStringify(Symbol("test")); // "Symbol(test)"
const circular: any = {};
circular.self = circular;
safeStringify(circular); // "[Complex Object]"