Typescript编译器不检查方法'返回类型的有效性(Typescript compiler does not check validity of method' return

编程入门 行业动态 更新时间:2024-10-23 17:39:33
Typescript编译器不检查方法'返回类型的有效性(Typescript compiler does not check validity of method' return type)

这是我的问题:我有一个实现接口的类。 方法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'.

更多推荐

本文发布于:2023-07-25 22:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267194.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:编译器   有效性   类型   方法   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!