6.x)
将ES6与
@types
支持和键入脚本。
图书馆的目标是扩展
Request
输入自
express
我创建了一个新的Node.js项目并添加了这个
tsconfig.json
:
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"sourceMap": true,
"declaration": true,
"outDir": "./dist",
"strict": true,
"types": ["mocha"]
}
}
package.json
:
{
"name": "@myscope/my-lib",
"main": "dist",
"scripts": {
"build": "rm -rf ./dist && ./node_modules/.bin/tsc",
"test": "./node_modules/.bin/mocha test"
},
"private": true,
"dependencies": {
"joi": "11.4.0"
},
"devDependencies": {
"mocha": "^5.2.0",
"express": "^4.16.4",
"@types/express": "^4.16.1",
"@types/joi": "^14.3.0",
"@types/mocha": "^5.2.5",
"typescript": "^3.2.4"
}
}
我的文件夹结构如下:
- dist
- src
- http
- security
- test
我创建了一个新的TypeScript文件
AuthenticatedRequest.ts
src/http
import {Request} from "express";
import {UserReference} from "../security/UserReference";
export interface AuthenticatedRequest extends Request {
user: UserReference
}
src/security
包含
UserReference.ts
import {Claim} from "./Claim";
export interface UserReference {
claims: Claim[];
}
Claim.ts
:
import {IClaim} from "./IClaim";
export class Claim implements IClaim {
type: string;
value: string;
constructor(type: string, value: string) {
this.type = type;
this.value = value;
}
}
IClaim.ts
看起来像这样:
export interface IClaim {
type: string,
value: string
}
在里面
test
,我创造了
AuthenticatedRequestTests.js
(纯ES6,此处没有用于验证代码完成和ES6使用的类型脚本):
'use strict';
const assert = require('assert');
const Claim = require("../dist/security/Claim").Claim;
describe('req', () => {
it('should ', done => {
/** @type {AuthenticatedRequest} */
const req = {};
req.user = { claims: [new Claim('tenantId', '123')] };
assert.equal(req.user.claims[ 0 ].type, 'tenantId');
assert.equal(req.user.claims[ 0 ].value, '123');
return done();
});
});
-
-
是否可以只使用
require("../dist/security/Claim");
而不是
require("../dist/security/Claim").Claim;
-
jsdoc
陈述
/** @type {AuthenticatedRequest} */
我想用
/** @type {myLib.http.AuthenticatedRequest} */
我还创建了一个本地集成测试项目,并通过
npm link
.
const Claim = require("@scope/my-lib/security/Claim").Claim;
我必须使用
const Claim = require("@scope/my-lib/dist/security/Claim").Claim;
dist
此外,使用
AuthenticatedRequest
在集成测试项目中,我发现找不到类型的错误: