Skip to main content
Version: Next

Function: createCodec()

createCodec<T>(encode, decode): Codec<T>

Defined in: src/Mnemonic/codecs.ts:142

Factory function for creating custom codecs.

Creates a Codec<T> from separate encode and decode functions. This is useful for implementing custom serialization strategies for types that aren't supported by JSONCodec. Using a custom codec on a key opts out of JSON Schema validation for that key.

Type Parameters

Type ParameterDescription
TThe TypeScript type of values to encode/decode

Parameters

ParameterTypeDescription
encode(value) => stringFunction that converts a typed value to a string
decode(encoded) => TFunction that converts a string back to a typed value

Returns

Codec<T>

A Codec<T> object compatible with useMnemonicKey

Examples

// Codec for Date objects
const DateCodec = createCodec<Date>(
(date) => date.toISOString(),
(str) => new Date(str)
);

const { value, set } = useMnemonicKey('lastLogin', {
defaultValue: new Date(),
codec: DateCodec
});
// Codec for Set<string>
const StringSetCodec = createCodec<Set<string>>(
(set) => JSON.stringify(Array.from(set)),
(str) => new Set(JSON.parse(str))
);

const { value, set } = useMnemonicKey('tags', {
defaultValue: new Set<string>(),
codec: StringSetCodec
});

See

  • Codec - The codec interface
  • CodecError - Error to throw when encoding/decoding fails
  • JSONCodec - Built-in codec for JSON values