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

递归映射类型触发自引用循环错误,如何适配递归字段?

解决递归映射类型中的循环引用问题

你遇到的循环引用错误,根源是原StandardType的条件判断逻辑把递归调用直接塞进了联合类型里,TypeScript无法解析这种嵌套递归的映射。下面是修复方案:

修复后的递归映射类型

// 定义允许的基础原子类型
type Primitive = number | string | boolean | null;
// 定义基础原子类型的数组
type PrimitiveArray = Array<number> | Array<string> | Array<boolean>;

type StandardType<T> = {
  [K in keyof T]: 
    // 优先匹配基础类型和基础类型数组,直接保留原类型
    T[K] extends Primitive | PrimitiveArray 
      ? T[K] 
      // 处理对象/数组类型,递归应用StandardType
      : T[K] extends object 
        ? StandardType<T[K]> 
        // 不符合规范的类型转为never
        : never;
}

修复逻辑说明

把原有的单层联合判断拆成分层逻辑:

  • 先处理简单的原子类型和原子数组,避免递归逻辑干扰
  • 再单独对对象/数组类型递归应用StandardType,让TypeScript能正确识别递归边界,不会触发循环引用错误

适配泛型类的使用

用修复后的StandardType,原有的Person接口和TestClass可以正常工作:

interface Person {
    name: string;
    age: number;
    children: Array<Person>;
}

class TestClass<T extends StandardType<T>> {
    constructor(person: T) {}
}

const test: TestClass<Person> = new TestClass({
    name: "one",
    age: 30,
    children: [
        {
            name: "child",
            age: 5,
            children: [],
        }
    ]
});

如果更关注API返回值的类型验证,也可以直接把构造函数参数类型设为StandardType<T>,约束更直观:

class TestClass<T> {
    constructor(person: StandardType<T>) {}
}

// 使用时无需显式指定泛型,TypeScript会自动推导
const test = new TestClass({
    name: "one",
    age: 30,
    children: [
        {
            name: "child",
            age: 5,
            children: [],
        }
    ]
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:53:21