Search code examples
typescriptpg-promise

Why can't I import classes and enums from namespace?


I use Typescript with pg-promise and I don't quite understand why I can't import the various classes and enums as I usually do. Usually when I use a library, I import a type, use it and it works just fine. In the code below, I'm trying to create a "mode" to be used in my transactions, so I import TransactionMode and isolationLevel but they are actually undefined at run time (no errors during design time and compile time). esModuleInterop is true in my tsconfig.json.

import pgPromise, { isolationLevel, TransactionMode } from "pg-promise";

const pgp = pgPromise();

// Doing this works, but I don't understand why it's necessary.
// const { TransactionMode, isolationLevel } = pgp.txMode;

// Here the imported TransactionMode and isolationLevel are undefined
const mode = new TransactionMode({ tiLevel: isolationLevel.serializable });

(...)

to be used in my code, instead having to pull the name


Solution

    • To import independently:
    import {txMode} from 'pg-promise';
    
    const {TransactionMode, isolationLevel} = txMode;
    
    • To import from the root interface:
    import * as pgPromise from 'pg-promise';
    
    const {TransactionMode, isolationLevel} = pgPromise.txMode;
    

    why I can't import the various classes and enums as I usually do?

    Because pg-promise is a JavaScript library, with some TypeScript declarations on top of it, it is not a native TypeScript module. In fact, it was written so long ago, no TypeScript existed back then.

    P.S. I'm the author of pg-promise.

    UPDATE

    Following this, txMode declaration has been updated, which now avoids the original issue.