2016-03-29 5 views
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インスタンス化があるため、エラーをスローすることを期待必要なコンストラクタインターフェイスがありません。私は間違って何をしていますか?ここで

答えて

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

window.addEventListener('resize',()=>{}); // This is an allowed use 
+0

偉大を使用する必要がない場合でも、イベントハンドラのようなもののため(evt)=>例えば行う必要があるでしょう!あなたが関数について話すとき、私はあなたがImproperpointクラスのコンストラクタを参照していると仮定します。 – vijayshan

+0

はい。 'constructor'は' new 'で呼び出さなければならない関数です。 – basarat

+0

これは言語の定義方法ですが、間違っているようです。 Typescriptはオプションのパラメータをサポートしています。あなたのイベントの例では、イベントハンドラ関数の宣言で 'evt'をオプションにしたい場合は、オプションとして宣言してください。オプションとして宣言されていない場合、コンパイラはオプションとして扱うべきではありません。 – RJM

関連する問題