node.js - index.d.ts typdefinitioner ignoreras av tsc vid kompilering


Jag har en Express-app byggd i TypeScript som jag försöker kompilera med tsc-kommandoradsverktyget.

Ett problem som jag däremot ställs inför är att tsc verkar ignorera index.d.ts-filen som jag har skapat och använt för att ändra Express Request-objektet.

Det här är min index.d.ts-fil:

declare global{
    namespace Express{
        export interface Request{
            foo: string;
        }
    }
}

Detta gör att jag kan göra saker som detta i mina controllers förfrågningar utan att TypeScript visar ett finns inte-fel:

export const example = async (req: Request) => {
    const { foo } = req;
    // Outputs "bar". This works completely fine in development.
    console.log(foo);
};

Jag kör följande kommando för att bygga min app:

tsc ./Main.ts --outdir build

Vilket resulterar i följande fel flera gånger på varje kontroll som använder det:

error TS2339: Property 'foo' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

Svar #1

Försök att lägga till en tom export i din index.d.ts-fil:

export {};

declare global{
    namespace Express{
        export interface Request{
            foo: string;
        }
    }
}