简体   繁体   English

TypeScript不强制执行接口

[英]TypeScript not enforcing interfaces

Consider the interface CommicBookCharacter 考虑接口CommicBookCharacter

interface CommicBookCharacter {
    name: string;
    fight : (nemisis: CommicBookCharacter) => void;
}

Which may be implemented by both heros and villian. 英雄和平民都可以实施。 Besides of these characters, there are also civilians 除了这些角色,还有平民

class Civilian{
    constructor(public name: string) {}
}

and here is how a hero could be implemented 这是英雄的实现方式

class SuperHero implements CommicBookCharacter {
    fight: (villian: Civilian) => void;

     constructor(public name: string) {
        this.fight = (hero)=> {
            alert(this.name + ' is struggling back');
        };
    }
}

Lets create some characters as well 让我们也创建一些角色

var spiderMan= new SuperHero('Spider Man');
var mj = new Civilian('Mary Jane');

Here is my problem. 这是我的问题。 The civilian class does not implement the ComicBookCharacter interface, but the SuperHero can still implement the fight method with the Civilian argument. 平民类没有实现ComicBookCharacter接口,但是SuperHero仍然可以使用Civilian参数来实现Fight方法。

This results in some bad problems: 这会导致一些严重的问题:

spiderMan.fight(mj);

As a side note: if I would change the type of villian in the SuperHeru class to, say string, it would give me an compilation error. 附带说明:如果我将SuperHeru类中villian的类型更改为字符串,则将出现编译错误。 In my opinion, this is a buggy behavior. 我认为,这是一种越野车行为。 SpiderMan should not be able to fight Mary Jane! SpiderMan应该无法与Mary Jane战斗!

You are explicitly accepting a Civilian as an argument : 您明确接受“ Civilian作为参数:

interface ComicBookCharacter {
    name: string;
    fight: (nemisis: ComicBookCharacter) => void;
}

class Civilian{} 

class SuperHero implements ComicBookCharacter {    
    name:string;
    // You explicitly accept Civilian
    fight = (villian: Civilian) => {}; 
}

This interface implementation is allowed since function argument types are bivariant, (as pointed out by Ryan) 允许此接口实现,因为函数参数类型是双变量的(如Ryan所指出的)

PS: Related https://typescript.codeplex.com/workitem/2282 In particular : https://typescript.codeplex.com/workitem/2282#CommentContainer6 PS:相关https://typescript.codeplex.com/workitem/2282特别是: https : //typescript.codeplex.com/workitem/2282#CommentContainer6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM