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

如何创建可阻止循环引用的TypeScript泛型?

如何用泛型阻止任意深度/类型的循环引用变量?

能不能创建一种泛型来阻止循环变量?无论循环引用的深度或类型如何,该泛型都应生效,而非仅针对T本身……

我目前实现了如下代码:

export type IsEqual<A, B> =
    (<G>() => G extends A ? 1 : 2) extends
    (<G>() => G extends B ? 1 : 2)
    ? true
    : false;

    
type DisallowCircular<T> = {
    [K in keyof T]: true extends IsEqual<T[K], T> ? never : T[K]
};

function noCircularAllowed<T extends DisallowCircular<T>>(a: T) {

}

class Foo {
    abc: string;
    circular: Foo;

    constructor() {
        this.abc = "Hello";
        this.circular = this;
    }
}

const foo = new Foo()

noCircularAllowed(foo)

这段代码可以成功禁止将foo作为输入,因为它存在自循环依赖。

  • 编辑2:之前表述不够清晰,现已明确需求:不仅要阻止赋值,还要阻止将此类变量传入函数等操作。
  • 编辑3:Jcalz指出当前实现会误判递归值而非仅自引用,这并非预期行为。理解该问题后,我意识到这个需求目前无法实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:45:10