2015-12-05 111 views
0

我曾尝试下面的代码的那些从打字稿编译没有错误:当构造函数接受不同的参数类型,从实现的接口

interface IRectangle { 
    height: number; 
    width: number; 
    getArea:()=>number; 
} 

module Shapes { 
    export class Rectangle implements IRectangle { 
     constructor(public height, public width) { 
     } 

     getArea() { 
      return this.width * this.height; 
     } 
    } 
} 

console.log(new Shapes.Rectangle(12, 'a').getArea()); 

我期待,试图当打字稿编译器应该给我一个错误为构造函数提供一个字符(最后一行代码)甚至难以接口(IRectangle)说这两个字段都应该是数字类型。但我没有收到任何错误。为什么背后的原因是?

回答

2

如果你想打字稿编译器看到这个错误,你可以宣布你的构造类似的构造(公众高度:数量,公共宽度:数)

要理解,为什么它不会在你的例子做有是一个很好的解释here

and here在类的静态端和实例端有一个重要的区别。希望有所帮助。

+0

感谢您强调静态和实例之间的区别,现在它是有道理的。 – Marius

相关问题