node-crc icon indicating copy to clipboard operation
node-crc copied to clipboard

Dynamically import crc algorithm

Open Abhishek-Kumbhani opened this issue 2 years ago • 1 comments

I am developing an application that uses this lib, in which I have given the support of multiple CRC algorithms, and when users finally run the config they created, those data is passed to a function, in which data to apply crc and algorithm and it returns calculated crc

import * as crc from 'node-crc';

const crcRunner = (props: { bufferData: Buffer; algoSubType: string }) => {
  const { bufferData, algoSubType } = props;

  const crcAlgo = crc.[algoSubType]

  return '';
};

here when I try to use the CRC algorithm, it throws an error of

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'type of import("c:/Abhishek/Projects/fuota.io-binary-preparation-tool/node_modules/node-crc/lib/lib")'. No index signature with a parameter of type 'string' was found on type 'type of import("c:/Abhishek/Projects/fuota.io-binary-preparation-tool/node_modules/node-crc/lib/lib")'

Can somebody help me with this problem?

Abhishek-Kumbhani avatar Sep 06 '23 05:09 Abhishek-Kumbhani

I'm not sure what you were trying to do, but maybe you want the following code,

const crcRunner = (props: { bufferData: Buffer; algoSubType: string }) => {
    const { bufferData, algoSubType } = props;

    const crcAlgo = (crc as unknown as Record<string, (data: Buffer) => Buffer>)[algoSubType];

    if (typeof crcAlgo === "function" && algoSubType !== "crc") {
        return crcAlgo(bufferData);
    } else {
        return null;
    }
};

magiclen avatar Sep 25 '23 16:09 magiclen