gpt4 book ai didi

typescript - 使用类表达式时是否支持循环引用?

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:43 24 4
gpt4 key购买 nike

在使用类表达式时,我在处理循环引用时遇到了一些问题。我正在动态生成类并尝试正确键入它们。

循环引用适用于类声明。

我想做的事情可行吗?

// Works
class X {
y?: Y;
}
class Y {
x?: X;
}

// Works without circular ref
const I = class {
};
const J = class {
i?: typeof I;
};


// Doesn't work with circular ref
const A = class {
b?: typeof B;
};
const B = class {
a?: typeof A;
};

Typescript playground


上下文更新

我正在尝试创建一个函数,该函数根据给定的“模型定义”生成一个类。这个模型定义有 bool 值、字符串、数字等类型,但也可能与另一个模型有关系。

只要不引入循环引用,它就类型而言工作正常。

playground说明了我正在努力完成的事情。

最佳答案

在对 TypeScript 语言规范进行了一些研究之后,我认为很遗憾,无法将循环类型引用与类表达式一起使用。

我无法根据您提供的信息判断您的一般方法是否正确 - 例如如果你真的需要类表达式、动态模型或者它是一个 XY 问题。那是另一个话题了。我在这里尝试的是回答为什么您使用循环类型引用和类表达式的方法会产生编译错误。

当类表达式 AB 通过 typeof A/typeof B 相互引用时,您创建类型typeof 运算符的别名。对于类型别名,规范说:

It is an error for the type specified in a type alias to depend on that type alias. Link

但是,还声明了以下内容:

Note that object type literals, function type literals, and constructor type literals do not depend on types referenced within them and are therefore permitted to circularly reference themselves through type aliases. Link

我是这样解释这个陈述的:如果你用上面提到的类型文字之一包装/替换你的模型引用,那么循环引用是可以的。

Modified Playground

在此示例中,我将您的模型类构造包装在工厂方法/函数类型文字中。它仅用于演示目的和工作,请随意以您自己的方式解释它。

假定您可以稍微调整 FieldDescriptor:

type FieldDescriptor = keyof MapSchemaTypes | (() => ModelConstructor<any>);

关于类声明:我想它们在您的示例中有效,因为类声明和接口(interface)支持为 Recursive Types .另见 this statement来自 TypeScript 首席开发人员。

希望这对您的情况有所帮助。

关于typescript - 使用类表达式时是否支持循环引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57246429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com