Protocol Methods
Built-in protocol methods for string coercion, JSON serialization, and primitive conversion of Color instances.
Protocol Methods
These methods implement JavaScript's built-in protocols, enabling Color instances to behave naturally in string interpolation, JSON serialization, and type coercion contexts.
toString()
Returns the Hex8 representation of the color. Automatically invoked in string contexts.
Signature
toString(): stringReturns
string: TheHex8representation of the color (e.g.,#FF0000FF).
Invoked By
String(color)- Template literals:
`${color}` Object.prototype.toString()
Example
playground.ts
toJSON()
Returns the Hex8 representation for JSON serialization. Automatically invoked by JSON.stringify().
Signature
toJSON(): stringReturns
string: TheHex8representation of the color (e.g.,#FF0000FF).
Invoked By
JSON.stringify()
Example
playground.ts
[Symbol.toPrimitive]()
Handles type coercion when the engine needs a primitive value. Returns different representations based on the requested hint.
Signature
[Symbol.toPrimitive](hint: string): string | number | ColorParameters
| Parameter | Type | Description |
|---|---|---|
hint | string | The coercion hint: "string", "number", or "default". |
Returns
| Hint | Return Type | Value |
|---|---|---|
"string" | string | The Hex8 representation. |
"number" | number | Integer parsed from the hex value (Hex6 if fully opaque, Hex8 otherwise). |
"default" | Color | The Color instance itself. |
Example
playground.ts
Last updated: Tue, Jun 16, 2026 04:43:07AM (UTC)
