TypeScript Generics

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • The generic types declared within the triangle brackets: <T>
  • Constrainting the generic types is done with the extends keyword: <T extends Car>

Remarks

The generic parameters are not available at runtime, they are just for the compile time. This means you can't do something like this:

class Executor<T, U> {
    public execute(executable: T): void {
        if (T instanceof Executable1) {    // Compilation error
            ...
        } else if (U instanceof Executable2){    // Compilation error
            ...
        }
    }
}

However, class information is still preserved, so you can still test for the type of a variable as you have always been able to:

class Executor<T, U> {
    public execute(executable: T): void {
        if (executable instanceof Executable1) {
            ...
        } else if (executable instanceof Executable2){
            ...
        } // But in this method, since there is no parameter of type `U` it is non-sensical to ask about U's "type"
    }
}


Got any TypeScript Question?