问题
`
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
declare module 'kvl' {
export = kvl;
}
declare const kvl : {
ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void;
}
`
Exports and export assignments are not permitted in module augmentations.
I was declared in .d.ts, Can't I use it like this?
回答1:
Module Augmentation:
Typescript calls this a module augmentation: You are using an existing module and add new definitions to it. Module augmentations have their own syntax:
- the module that your declare must have the same name as the augmented module
- inside the module you can't export anything
This is described here: https://github.com/Microsoft/TypeScript-Handbook/blob/fa9e2be1024014fe923d44b1b69d315e8347e444/pages/Declaration%20Merging.md#module-augmentation
Following the docs, your code becomes this:
// file1.ts
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
// module name must be "express"
declare module 'express' {
// this can't be an export
const kvl : {
ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void;
}
}
Now you have augmented the express
module and can use it like this:
// file2.ts
import {kvl} from "express";
// ...
Modular Declaration File:
If you don't want to inject your new types into the express module, you can use a declaration file for your new module. There are various types, a good overview can be found here: https://www.typescriptlang.org/docs/handbook/declaration-files/library-structures.html
Basically, you have to check how the code is used and then adapt your declarations to that. In your case, it looks like you want to import kvl
as a module. So you can orient yourself on this sample file: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html
I have changed your code to the appropriate syntax. By the way, this is only correct in a .d.ts file:
//kvl.d.ts
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
export as namespace kvl;
export const kvl : {
ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void;
};
Implementing a Module:
If kvl
is your own code, then you don't have to work with declaration files. Typescript can analyze your modules. A module definition that would produce a kvl constant with proper type could look like this:
// kvl.ts
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
export const kvl : {
ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void;
} = {ValidationDone: function(param){}};
Please note that modules automatically have their filename as modulename. Therefore, the above code should be in a file called kvl.ts.
来源:https://stackoverflow.com/questions/53186841/exports-and-export-assignments-are-not-permitted-in-module-augmentations