我正在尝试为我的项目添加一个构造函数接口,并且为什么下面的代码没有抛出错误我感到非常困惑:
interface PointConstructor{
new(x:number, y:number, z:number):point;
}
interface point{
x:number;
y:number;
z:number;
move_1();
}
class TwoDPoint implements point{
x: number;
y: number;
z: number;
constructor(x:number, y:number){
this.x = x;
this.y = y;
}
move_1(){
this.x =this.x + 1;
this.y = this.y + 1;
}
}
class ThreeDPoint implements point{
x: number;
y: number;
z: number;
constructor(x:number, y:number, z:number){
this.x = x;
this.y = y;
this.z = z;
}
move_1(){
this.x++;
this.y++;
this.z++;
}
}
class improperpoint implements point{
x: number;
y: number;
z: number;
move_1(){
this.x++;
this.y++;
this.z++;
}
}
function constructPoint(ctor:PointConstructor, x:number,y:number, z:number=0):point{
return new ctor(x,y,z);
}
let a = constructPoint(TwoDPoint, 0,0)
let b = constructPoint(ThreeDPoint, 0,0,0);
let c = constructPoint(improperpoint, 0,0,0);
console.log(`Point x ${a.x} Point Y ${a.y} Point z ${a.z}`);
console.log(`Point x ${b.x} Point Y ${b.y} Point Z ${b.z}`);
a.move_1()
b.move_1();
console.log(`Point x ${a.x} Point Y ${a.y} Point z ${a.z}`);
console.log(`Point x ${b.x} Point Y ${b.y} Point Z ${b.z}`); x ${b.x} Point Y ${b.y} Point Z ${b.z}`);
在前面的代码中,我期望不正确的实例化会抛出错误,因为它没有所需的构造函数接口。我做错了什么?
答案 0 :(得分:1)
以下是代码的简化版本,显示了您预期错误的位置:
interface PointConstructor {
new (x: number): Point;
}
interface Point {
x: number;
}
class ImproperPoint implements Point {
x: number;
}
let ctor: PointConstructor = ImproperPoint; // You expect an error here
它没有错误的原因是因为可以使一个函数占用比TypeScript中提供的更少的参数。
这是为了方便起见。否则,即使您不需要使用(evt)=>
evt
。
window.addEventListener('resize',()=>{}); // This is an allowed use