Ts有趣现象之没有实现接口,却可以通过编译并正常执行
今日学习Ts的接口,我发现了一个有趣的Ts怪像,直接上代码
interface animalConstructor {
new (name:string,sing:string):animalInterface
}
interface animalInterface {
bark():void;
}
class Dog implements animalInterface{
name:string
sing:string
constructor(n:string,sing:string) {
this.name = n
this.sing = sing
}
bark() {
console.log(`${this.name}${this.sing}`)
}
}
class Cat {
name:string
sing:string
constructor(name:string,sing:string) {
this.name = name
this.sing = sing
}
bark(): void {
console.log(`${this.name}${this.sing}`)
}
}
/**
* 我发现个有趣的事情,即便类没有申明implement animalConstructor,但是自身的Constructor和animalConstructor一样,
* 也没有申明implement animalInterface ,只是存在同样的方法,也可以正常执行;Cat类什么也没申明实现,却可以正常运行
* */
function animalBark(animal:animalConstructor,n:string,s:string):animalInterface {
return new animal(n,s)
}
let dog = animalBark(Dog,'狗','汪汪')
let cat = animalBark(Cat,'猫','喵喵')
dog.bark()
cat.bark()
本文来自博客园,作者:勤匠,转载请注明原文链接:https://www.cnblogs.com/JarryShu/p/16986515.html