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

Type checking in hierarchy: getParentOfType()

我仍然对 TypeScript 的类型检查系统感到困惑。假设一个复合体包含一组元素,这些元素都来自一个公共基础 class。我怎样才能实现一个函数递归地上升到层次结构和 returns 给定类型的第一个锚点?

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. 'class type'的类型不能声明为typeof Ttypeof in type position 仅适用于变量,不适用于类型。为此,您需要使用所谓的 constructor signature

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

  3. 您的代码中没有真正的递归 - 您总是为同一个 this 对象调用 getSuperiorOfType。您需要将其称为 this.Superior.getSuperiorOfType(...) 才能在层次结构中向上移动一级。

    abstract class Employee
    {
        public Superior: Employee;
    
        public getSuperiorOfType<T extends Employee>(type: { new(...args: any[]): T}): T
        {
            if (this instanceof type) return this;
            else if (this.Superior !== undefined) return this.Superior.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); 
    console.log(x === tom); // true