这是我的问题:我有一个实现接口的类。 方法greet应该有返回类型void但在我实现的类中它有string和编译器不警告我。 而IDE(我使用的是PhpStorm)。 我错过了什么或者这是故意的吗?
interface Person { sex: string; greet() : void; } class Boy implements Person { sex: 'M'; greet() { return this.sex; } }我正在使用Typescript 2.0.10
Here is my problem: I have a class which implements interface. Method greet should have return type void but in my implemented class it has string and compiler doesn't warn me. And IDE neither (I'm using PhpStorm). Am I missing something or is this intentional?
interface Person { sex: string; greet() : void; } class Boy implements Person { sex: 'M'; greet() { return this.sex; } }I'm using Typescript 2.0.10
最满意答案
它不会抱怨,因为它并不重要。 您的接口声明该方法返回void ,如果您的实现返回一个值,那么不会发生任何伤害。 例:
let person: Person = new Boy(); person.greet();由于person属于Person (而不是Boy ),因此greet方法不会返回值,实际上我并不是在尝试使用返回值。
另一方面,如果是相反的:
interface Person { sex: string; greet(): string; } class Boy implements Person { sex: 'M'; greet(): void {} }然后抛出一个错误:
类'Boy'错误地实现了接口'Person'。 属性'greet'的类型是不兼容的。 类型'()=> void'不能赋值为'()=> string'。 类型'void'不能分配给'string'类型。
It won't complain because it doesn't really matter. Your interface declares that the method returns void, if your implementation returns a value then no harm will happen. Example:
let person: Person = new Boy(); person.greet();As person is of type Person (and not Boy) then the greet method won't return a value, and indeed I'm not trying to use a return value.
On the other hand if it was the opposite:
interface Person { sex: string; greet(): string; } class Boy implements Person { sex: 'M'; greet(): void {} }Then an error is thrown:
Class 'Boy' incorrectly implements interface 'Person'. Types of property 'greet' are incompatible. Type '() => void' is not assignable to type '() => string'. Type 'void' is not assignable to type 'string'.
更多推荐
发布评论