String coercion
Certain methods like concat will coerce their argument values to a string type before operating on them.
However, TypeScript will often enforce a more restrictive type on the arguments to these functions.
Loading TypeScript...
Rules of string coercion
undefinedbecomes"undefined"andnullbecomes"null"truebecomes"true", andfalsebecomes"false"- Strings are returned as-is
- Numbers and BigInt are converted with
.toString(10)(i.e. decimal representation) - Symbols will throw a
TypeError - Objects are first converted to a primitive value by calling
[Symbol.toPrimitive](), in most cases with"string"as a hint.
Loading TypeScript...
If a conversion function is not defined, the primitive value is retrieve from toString() or valueOf(), in that order. The resulting primitive value is then converted to a string.
Loading TypeScript...
Adding an empty string
It is common to see JavaScript programs that coerce a number to a string by adding the empty string "".
For readability reasons alone, it is better to use the String function or toString to convert a number to a string.