I have a library written in js that helps pack and unpack Buffer
s. It uses the builder pattern:
const bufferFormat = buffer() .int8('id') .int16('subchannel') .int32('channel') .int32('connectionId') .varString('message'); const buff = Buffer.from(...); const obj = bufferFormat.unpack(buff); /* typeof obj === { id: number; subchannel: number; channel: number; connectionId: number; message: string; } */ const buffOut = bufferFormat.pack({ id: 1, subchannel: 2, connectionId: 3, message: 'message', });
I want to add types to this, and ideally have it implicitly figure out the object types. The way I'm thinking of doing this is change the formatter from being builder style to taking in an array of formats in the constructor:
const bufferFormat = new BufferFormat([ { type: 'int8', name: 'id', }, { type: 'int16', name: 'subchannel', }, { type: 'string', name: 'message', }, ]);
And then implicitly determining the pack/unpack object type to be
interface { id: number; subchannel: number, message: string, }
This would require me to be able to infer an object type from an array of objects. Is this possible to do with typescript? Or will I have to come up with another way to add types to this buffer formatter?