0

I have a type inside a block, but I want to reference it from an external block. In this example I have a drizzle ORM query which generates a well defined type, which I want to use in the calling function:

function a() = {
    const emisor = db.query.registro.findFirst({
        where: eq(registro.nrc, '1234'),
        with: {
            actividad: true,
            municipio: true
        }
    });

    type Emisor = typeof emisor;

    processDTE(emisor);
};

function processDTE(emisor){

   // Do more stuff

}

Ideally I want to do something like function processDTE(emisor: Emisor) but I cannot reference Emisor from an external block.

Editing to a minimal reproducible example:

    function start() {
        const variable = { a: 'Some object with a complex structure....' };
        type myType = typeof variable;
        process(variable);
    }

    function process(variable: myType) {
        variable.a = 'Something';
    }

I left drizzle in the first example, in case someone knows the "Drizzle" way to do this. But the main problem is that I want to use a type myType which was created inside a block, but I want to use it outside the block.

Of course this example function process(variable: myType) will not work as myType is not scoped for this.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Ben Quan
  • 773
  • 11
  • 25
  • `ReturnType` I guess – Dimava Aug 16 '23 at 20:38
  • @Dimava Right, unless it's generic or overloaded or ... I wouldn't want to speculate too much without a [mre]. – jcalz Aug 16 '23 at 20:40
  • There's no way to export a type from a function scope (there's a request at [ms/TS#31160](https://github.com/microsoft/TypeScript/issues/31160) for that but it's not part of the language). The "right" thing to do is define the type in the outer scope and then use it in the inner scope, which might be redundant but is at least straightforward. Otherwise you will play weird scope games I can't really recommend. See [this playground link](https://tsplay.dev/weLreW) for examples. Does that fully address the question? If so I'll write up an answer explaining; if not, what am I missing? – jcalz Aug 16 '23 at 23:53

0 Answers0