Search code examples
typescriptbn.js

TypeScript and "bn.js" - should I use 'typeof BN' or the BN Constructor?


Note: I know we shouldn't be using bn.js and just use BigInts but I have a legacy codebase and haven't migrated off it yet.

The following code compiles and runs perfectly:

import { BN } from "bn.js";
import assert from "node:assert/strict";

const one = new BN(1);

one.cmp(one);

export const assertBigNumberEqual = (actual: BN, expected: BN) => {
  return assert(actual.cmp(expected) === 0);
};

console.log("this will work");
assertBigNumberEqual(new BN(1), new BN(1));
console.log("yay it worked");

console.log("this will throw an error");
console.log(assertBigNumberEqual(new BN(1), new BN(2)));

However on this function, TS warns:

export const assertBigNumberEqual = (actual: BN, expected: BN) => {
  return assert(actual.cmp(expected) === 0);
};

'BN' refers to a value, but is being used as a type here. Did you mean 'typeof BN'? ts(2749)

If I use typeof BN in the parameters, however, actual.cmp won't work.

I don't want to use @ts-ignore but instead I want to fix the error.

How do I fix the TypeScript warning?


Solution

  • BN's export is declared as

    export = BN;
    

    considering you have allowSyntheticDefaultImports enabled, you should change your import as

    import BN from "bn.js";
    

    as otherwise you refer to the static property BN of the BN class

    TS Play