程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了递归/圆形相交大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决递归/圆形相交?

开发过程中遇到递归/圆形相交的问题如何解决?下面主要结合日常开发的经验,给出你关于递归/圆形相交的解决方法建议,希望对你解决递归/圆形相交有所启发或帮助;

我有以下类型构造:

class StartClass {
  [propertyname: String]: nestedClass; // We can have multiple nestedClasses here with any names

  ...
}

class nestedClass {
  active: Boolean; // error: not assignable ...
  blackList?: String[]; // error: not assignable ...
  [propertyname: String]: nestedClass; // nestedClass itself can contain multiple nestedClass fIElds with any names

  ...
}

我收到如下编译器错误:Property 'blackList' of type 'String[] | undefined' is not assignable to String index type 'nestedClass'.。 我的第一个想法(这可能是完全错误的)是创建一个像这样的交集:

type intersected = nestedClass & {[propertyname: String]: nestedClass}

尽管我不确定这是正确的方法,但它会导致编译器错误 Type alias 'Intersected' circularly references itself.

那么,有没有办法在 TypeScript 中声明这样一个用 nestedClass 勾画的结构?

解决方法

我想这个问题的答案是,自 TypeScript 4.0 以来,您确实可以像这样在 TypeScript 中编写递归交集:

type Foo = { a: String } & { [k: String]: Foo }; // works

declare const foo: Foo;
foo.a.toUpperCase();
foo.bar.a.toUpperCase();

Playground link to code

不打算在这里详细说明为什么这种类型有问题,因为 OP 已经知道这一点,而且在这里有点超出范围;对于那些感兴趣的人,您可以在 Stack Overflow 问题中阅读 "How to define Typescript type as a Dictionary of Strings but with one numeric “id” property"。


自从 TypeScript 3.7 引入对 more recursive type aliases 的支持以来,这 应该就可以工作了,但是有一个错误阻止了这个案例的工作。它在 microsoft/TypeScript#38672 中报告并在 microsoft/TypeScript#38673 中修复,使其成为 TypeScript 4.0。

这意味着如果您收到此代码的错误,则您使用的是 4.0 之前的 TypeScript 版本,并且可能想在有机会时虑升级,因为语言变化相当快。


如果您必须在较早版本的 TypeScript 中使用这样的东西,您可以做以下丑陋的事情:

type _Foo = { a: String,[k: String]: unknown };
type Foo = { [K in keyof _Foo]: String extends K ? Foo : _Foo[K] };
/* type Foo = {
    [x: String]: Foo;
    a: String;
} */

declare const foo: Foo;
foo.a.toUpperCase();
foo.bar.a.toUpperCase();

Playground link to code

您可以通过对具有一致索引签名的类型进行 mapping 来欺骗编译器允许不一致的索引签名,并对属性执行不一致的 conditional type。因此,我采用了 {a: String,[k: String]: unknown},一个完全有效的类型,并对其进行映射以生成 Foo,尽管您无法直接编写此类型,但其类型看起来是 {[x: String]: Foo,a: String}。>


我真的不知道我是否会推荐一个依赖于欺骗编译器的解决方案,所以如果可能的话,你仍然应该虑升级到 TS4.0+,或者甚至可能完全放弃这种类型,转而使用 TypeScript可以处理。

大佬总结

以上是大佬教程为你收集整理的递归/圆形相交全部内容,希望文章能够帮你解决递归/圆形相交所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: