Skip to content

webshrine / stdtyp/src / SerializableToPrimitive

Interface: SerializableToPrimitive

Defines a type that can be serialised to a primitive via the Symbol.toPrimitive method or implicit type conversion

See

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive

Example

ts
class SomeObject implements SerializableToPrimitive {
  [Symbol.toPrimitive] = (hint) => {
    switch (hint) {
      case 'number':
        return 123
      case 'string':
        return 'SomeObject[...]'
      default:
        return 'SomeObject[...]'
    }
  }
}

const str = new SomeObject() + '' // 'SomeObject[...]'
const num = new SomeObject() * 1 // 123

#interface #atom #serialisation

Properties

[toPrimitive]()

[toPrimitive]: (hint) => Primitive

Parameters

hint

ToPrimitiveHint

Returns

Primitive

Throws

TypeError

Defined in

packages/stdtyp/src/interfaces/index.ts:84