How to make sure the generic type T
implements a certain property?
export class Helicopter<T> implements IFlyable<T> {
constructor(private _value : T) {
}
get listOfEngines(): string[] {
return _value.listOfEngines;
}
}
Currently, the compiler complains the type T
has no property listOfEngines
What you are looking for is called constraining:
https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints
Just specify the type or interface T must extends as shown in the manual.
export class Helicopter<T extends IVehicle> implements IFlyable<T> {}
Create an interface and add an extends
restriction to the type parameter T
:
export interface IHelicopterStructure {
listOfEngines:string[];
}
export class Helicopter<T extends IHelicopterStructure> extends Structure implements IFlyable<T> {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With