如果我将TypeScript模块保存为my-function.ts,如下所示:
export function myFunction (param: number): number { return param }
这将以任何方式编译为JavaScript并且松散其类型定义。然后我可以创建一个index.d.ts文件来声明这个模块的定义,但重新定义/重新定义这些定义似乎有点乏味。
有没有办法从my-function.ts文件自动生成类型定义到index.d.ts文件?
如果使用--declaration
标志进行编译,TypeScript将自动为您生成.d.ts
文件。
此模式将要求您可以看到某些类型,以便可以在.d.ts
文件中对其进行描述。
我的tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./tsOutputs"
},
"include": [
"lib/**/*.ts",
"index.ts"
],
"exclude": [
"test/**/*.ts"
]
}
注意:为了能够转换和创建对象的实例,每个实体需要有两个不同的导出。一次作为类型,另一个作为const。
这是我的index.ts:
import {HttpClient as HC} from "./lib/http/http-client";
import {HttpRequest as HReq, HttpResponse as HRes} from "./lib/http/contracts";
export namespace MyJsInfra
{
export type HttpClient = HC;
export namespace Entities{
export type HttpRequest = HReq;
export const HttpRequest = HReq;
export type HttpResponse = HRes;
export const HttpResponse = HRes;
}
}`
您可以在此处阅读有关此双重声明背后的原因的更多信息:https://github.com/Microsoft/TypeScript/issues/10058#issuecomment-236458961
这是我的package.json:
{
"name": "my-js-infra",
"version": "1.0.0",
"description": "Infrastructure code.",
"scripts": {
"build":"./node_modules/.bin/tsc -p .",
"prepublish":"npm run build",
},
"homepage": "https://github.com/Nadav/My.JS.Infra#readme",
"devDependencies": {
...
"typescript": "^2.4.2",
...
},
"dependencies": {
...
"needle": "^1.4.2",
...
},
"files": [
"tsOutputs/**/*.js",
"tsOutputs/**/*.d.ts",
"tsOutputs/index.d.ts"
],
"types":"tsOutputs/index.d.ts",
"main":"tsOutputs/index.js"
}
全部完成。现在您可以发布您的公共代码。
npm install my-js-infra --save
这是我的tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"lib": ["es5", "es6"],
"module": "umd",
"sourceMap": true,
"watch": false,
"outDir": "./tsOutputs",
"moduleResolution":"node" /* This must be specified in order for typescript to find the my-js-infra. Another option is to use "paths" and "baseUrl". Something like:
...
"baseUrl": ".", // This must be specified if "paths" is used.
"paths":{
"my-js-infra":["node_modules/my-js-infra/tsOutputs/index.d.ts"]
}
...
*/
}
}
您可以在这里阅读有关模块分辨率的更多信息:https://www.typescriptlang.org/docs/handbook/module-resolution.html
import {MyJsInfra } from "my-js-infra";
public doMagic(cmd, callback) {
try {
var request:MyJsInfra.Entities.HttpRequest = {
verb: "GET",
url: "http://www.google.com",
};
var client = new MyJsInfra.HttpClient();
client.doRequest(request, (err, data)=>{
if (err)
return callback(err, null)
return callback(null, data);
})
} catch (err) {
callback(err);
}
}