泛型

通用引數在執行時不可用,它們僅用於編譯時。這意味著你不能做這樣的事情:

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

但是,類資訊仍然保留,因此你仍然可以測試變數的型別,因為你始終能夠:

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"
    }
}