Handle custom types with ExtensionCodec
mainTo support custom JavaScript/TypeScript classes (like Map, Set, or custom domain objects) that are not part of the standard MessagePack specification, use the ExtensionCodec class.
- Create an instance of
ExtensionCodec. - Register an extension using
.register({ type, encode, decode }). - Important: Custom extension types must use a type ID in the range
[0, 127]. The range[-1, -128]is reserved for MessagePack internals. - Important: When performing recursive encoding or decoding, you must pass the
extensionCodecinstance in theoptionsobject of theencodeordecodecalls.
import { encode, decode, ExtensionCodec } from "@msgpack/msgpack";
const extensionCodec = new ExtensionCodec();
// Example: Registering Set<T>
const SET_EXT_TYPE = 0;
extensionCodec.register({
type: SET_EXT_TYPE,
encode: (object: unknown): Uint8Array | null => {
if (object instanceof Set) {
return encode([...object], { extensionCodec });
} else {
return null;
}
},
decode: (data: Uint8Array) => {
const array = decode(data, { extensionCodec }) as Array<unknown>;
return new Set(array);
},
});
const encoded = encode([new Set<any>()], { extensionCodec });
const decoded = decode(encoded, { extensionCodec });