今日学习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()
标签:name,Ts,animalInterface,现象,sing,有趣,bark,string
From: https://www.cnblogs.com/JarryShu/p/16986515.html