You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript抽象工厂模式报错:TypeError: Class extends value undefined

TypeError: Class extends value undefined is not a constructor or null 错误排查与解决

错误原因

  1. 循环依赖导致模块加载顺序异常:
    抽象工厂类AnimalAbstractFactory提前导入了LandAnimalFactory和SeaAnimalFactory,而这两个子工厂又继承自AnimalAbstractFactory并反向导入它。这种循环依赖会导致模块加载时,子工厂尝试继承的AnimalAbstractFactory还未完成初始化,值为undefined,从而触发错误。
  2. 文件路径拼写错误:
    SeaAnimalFactory.ts中导入Octopus类时,路径写成了./Octobus,正确路径应为./Octopus(假设对应文件名为Octopus.ts)。
  3. 缺失依赖文件:
    代码中引用了Tiger.ts和Octopus.ts但未提供,若这两个文件不存在,会引发后续运行错误。

解决办法

1. 修复循环依赖

修改AnimalAbstractFactory.ts,移除对子工厂的静态导入,改用运行时动态导入创建实例,避免加载顺序冲突:

import { IAnimal } from "./IAnimal";

export default abstract class AnimalAbstractFactory{
 public abstract getAnimalType(animalname:string):IAnimal | null;
 public static createAnimalFactory(factoryType:string):AnimalAbstractFactory | null{
    if(factoryType == 'Land'){
        const { LandAnimalFactory } = require("./LandAnimalFactory");
        return new LandAnimalFactory();
    }else if( factoryType == 'Sea'){
        const { SeaAnimalFactory } = require("./SeaAnimalFactory");
        return new SeaAnimalFactory();
    }else{
        return null;
    }
 }
}

2. 修正文件路径

修改SeaAnimalFactory.ts中的导入路径:

// 原错误路径
// import { Octopus } from "./Octobus";
// 修正为
import { Octopus } from "./Octopus";

3. 补充缺失文件

确保Tiger.ts和Octopus.ts存在并正确实现IAnimal接口,示例如下:
Tiger.ts:

import { IAnimal } from "./IAnimal";

export class Tiger implements IAnimal{
   public getAnimal(): string {
       return "Tiger";
    }
}

Octopus.ts:

import { IAnimal } from "./IAnimal";

export class Octopus implements IAnimal{
   public getAnimal(): string {
       return "Octopus";
    }
}

验证运行

修改完成后,重新执行npx ts-node运行主驱动代码,即可正常输出Lion。

内容的提问来源于stack exchange,提问作者Js Sapien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 08:12:48