0
私は私のプロジェクトにコンストラクタインタフェースを追加しようとし、次のコードがエラーを投げていない理由としては非常に当惑していています:上記のコードでコンストラクタインターフェイスの混乱、なぜ次のコードはエラーを生成しないのですか?
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}`);
を私はimproperpointインスタンス化があるため、エラーをスローすることを期待必要なコンストラクタインターフェイスがありません。私は間違って何をしていますか?ここで
偉大を使用する必要がない場合でも、イベントハンドラのようなもののため
(evt)=>
例えば行う必要があるでしょう!あなたが関数について話すとき、私はあなたがImproperpointクラスのコンストラクタを参照していると仮定します。 – vijayshanはい。 'constructor'は' new 'で呼び出さなければならない関数です。 – basarat
これは言語の定義方法ですが、間違っているようです。 Typescriptはオプションのパラメータをサポートしています。あなたのイベントの例では、イベントハンドラ関数の宣言で 'evt'をオプションにしたい場合は、オプションとして宣言してください。オプションとして宣言されていない場合、コンパイラはオプションとして扱うべきではありません。 – RJM