[英]Typescript: Class that implements at least a specific interface
I have the following question. 我有以下问题。 Let's say i have an Interface like this 假设我有一个这样的接口
interface Animal<T>{
children: Array<T>
}
now i want to write a method which will later take in eg a bird (a class that implements Animal). 现在,我想编写一个方法,该方法以后将包含一个鸟(一个实现Animal的类)。 At the time writing the method the definition for bird does not exist yet. 在编写该方法时,鸟的定义尚不存在。 It could also be it would be given an instance of Shark. 也可能是它被赋予了Shark的实例。 But the minimal requirement will be that any object it receives will be an instance of a class that implements Animal. 但最低要求是,它接收的任何对象都将是实现Animal的类的实例。
function doSomething(AnAnimal){
//Do something with animal
}
// Implementation with a class that implements Animal
class Bird<T> implements Animal{
children: Array<T>;
color: string;
chirp(){console.log('peep')}
constructor(Color:string){
this.color = Color;
}
}
let tweety = new Bird('yellow');
doSomething(Tweety)
I hope I could make clear what I'm trying to do and you have an idea how i could solve this in TypeScript. 我希望我能弄清楚我要做什么,您对我可以在TypeScript中解决这个问题有个想法。
You need to flow your type arguments throughout your example... 您需要在整个示例中传递类型参数。
interface Animal<T>{
children: Array<T>
}
function doSomething<T>(arg: Animal<T>){
//Do something with animal
}
class Bird<T> implements Animal<T>{
children: Array<T>;
color: string;
chirp(){console.log('peep')}
constructor(Color:string){
this.color = Color;
}
}
let tweety = new Bird('yellow');
doSomething(tweety);
For example, Bird<T>
must implement Animal<T>
. 例如, Bird<T>
必须实现Animal<T>
。 The doSomething
function must be generic in order to deal with an argument of type Animal<T>
. 为了处理Animal<T>
类型的参数, doSomething
函数必须是通用的。
You might find that you are tying yourself up unnecesarily in type arguments here - so you might want to try the non-generic version. 您可能会发现您在这里不必要地在类型参数中使用了自己-因此您可能想尝试使用非通用版本。
interface Animal {
children: Array<Animal>;
}
function doSomething(arg: Animal) {
//Do something with animal
}
class Bird implements Animal {
children: Array<Bird>;
biggestEnemy: Animal;
color: string;
chirp() { console.log('peep') }
constructor(Color: string) {
this.color = Color;
}
}
let tweety = new Bird('yellow');
doSomething(tweety);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.