Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure generic type has certain property

Tags:

typescript

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

like image 595
Harald Thomson Avatar asked Dec 10 '15 13:12

Harald Thomson


2 Answers

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> {}
like image 171
L.Trabacchin Avatar answered Sep 29 '22 10:09

L.Trabacchin


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> {
    ...
}
like image 21
Michael Rose Avatar answered Sep 29 '22 12:09

Michael Rose