通过ts declare包装一个js库
myshape模块
0.npm init
- libs目录中新增3个js文件
point.js
class Point{
x = 0;
y = 0;
constructor(x,y) {
this.x = x;
this.y = y;
}
getDistance(other) {
let xDis = Math.abs(this.x - other.x);
let yDis = Math.abs(this.y - other.y);
return Math.sqrt(xDis*xDis + yDis*yDis);
}
}
module.exports = Point
circle.js
let Point = require('./point')
class Circle{
radius = 0;
point = null;
constructor(point, radius) {
this.radius = radius;
this.point = point;
}
isInCircle(point){
let dis = this.point.getDistance(point)
return dis <= this.radius;
}
}
module.exports = Circle
index.js
let Point = require('./point')
let Circle = require('./circle')
module.exports = {
Point,
Circle
}
package.json
{
"name": "myshape",
"version": "1.0.0",
"description": "",
"main": "./libs/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"files": ["libs"]
}
index.d.ts
declare module 'myshape' {
class Point{
constructor(x:number,y:number);
getDistance(other:Point):number;
}
class Circle{
constructor(point: Point, radius: number);
isInCircle(point: Point):boolean;
}
}
执行 npm link
### 测试myshape模块
0. npm init
- tsc --init
- npm link myshape
- 新建demo.ts
import {Point} from 'myshape'
let p:Point = new Point(2,3);
let p2:Point = new Point(1,2)
console.log(p.getDistance(p2));