层次结构中的类型检查:getParentOfType()

时间:2017-11-10 15:19:25

标签: typescript types typechecking

我仍然很难使用TypeScript的类型检查系统。假设一个复合体包含一组元素,这些元素都来自一个公共基类。如何实现递归上升到层次结构并返回给定类型的第一个anchestor的函数?

abstract class Employee
{
    public Superior: Employee;

    /** THIS IS NOT WORKING */
    public getSuperiorOfType<T extends Employee>( type: typeof T ): T
    {
        if (this instanceof T) return this;
        else if (this.Superior !== undefined) return this.getSuperiorOfType(type);
    }
}

class Manager extends Employee {}
class TeamLead extends Employee {}
class Developer extends Employee {}

let tom = new Manager();
let suzanne = new TeamLead();
let ben = new Developer();

ben.Superior = suzanne;
suzanne.Superior = tom;

let x = ben.getSuperiorOfType( Manager ); // x = tom

提前感谢您的帮助......

1 个答案:

答案 0 :(得分:1)

  1. &#39;类类型的类型&#39;不能声明为typeof T。类型位置中的typeof仅适用于变量,而不适用于类型。您需要使用所谓的constructor signature

    public getSuperiorOfType<T extends Employee>(type: { new(...args: any[]): T}): T
    
  2. 您无法检查对象是否为泛型类型参数的instanceof - instanceof T不起作用,因为运行时不存在泛型类型参数。但是您有[{1}}作为实际的函数参数,因此type应该有效。

  3. 您的代码中没有真正的递归 - 您始终为同一个instanceof type对象调用getSuperiorOfType。您需要将其称为this,以便在层次结构中向上移动一步。

    this.Superior.getSuperiorOfType(...)