TypeScript - 正确使用递归泛型

发布于 2025-01-12 21:08:39 字数 721 浏览 3 评论 0原文

我正在尝试以一种可以从编辑器获得很多帮助的方式使用递归泛型。

这是一个例子:

interface ServiceEndpointNode {
  self: string;
  context?: Record<string, ServiceEndpointNode>
}

const ServiceEndpoints: ServiceEndpointNode = {
  self: 'BASE_URL',
  context: {
    songs: {
      self: 'GET_SONGS',
      context: {
        getSong: {
          self: 'GET_SONG',
        },
        getContributors: {
          self: 'GET_CONTRIBUTORS',
        }
      }
    }
  }
}

这工作正常并且结构严格,但我没有得到编辑的帮助。例如,我想要这样的帮助:

ServiceEndpoints.context.songs.context.getsong.self

但是因为我只告诉打字上下文应该是一个字符串,所以我并没有真正收到有关可遍历对象的帮助。我想我需要包含一些泛型或其他东西,但不知道如何实现这一点。 :(

所以我想必须保持这个严格的结构,但从编辑器那里获得所有可能的路线、键等的帮助。

I am trying to use recursive generics in a way I can get a lot of help from editor.

Here is an example:

interface ServiceEndpointNode {
  self: string;
  context?: Record<string, ServiceEndpointNode>
}

const ServiceEndpoints: ServiceEndpointNode = {
  self: 'BASE_URL',
  context: {
    songs: {
      self: 'GET_SONGS',
      context: {
        getSong: {
          self: 'GET_SONG',
        },
        getContributors: {
          self: 'GET_CONTRIBUTORS',
        }
      }
    }
  }
}

This works properly and the structure is strict, but I don't got help from the editor. For example I want help like:

ServiceEndpoints.context.songs.context.getsong.self

But because I only told the typing that the context should be a string I don't really receiving help about the traversable object. I guess I need to be include some generics or something, but don't know how to achieve that. :(

So I want to have to maintain this strict structure, yet get help from the editor for all the possible routes, keys, etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋心╮凉 2025-01-19 21:08:39

现在您可以在 TypeScript 中使用可选链来简化,如下所示。这样打字稿编译器就会期望 NULL |欠款

    console.log(ServiceEndpoints.context?.songs.context?.getSong?.self);
    // OUTPUT: "GET_SONG" 

Now you can use Optional chaining in TypeScript simplify as shown below. So that typescript compiler will expect NULL | underfined

    console.log(ServiceEndpoints.context?.songs.context?.getSong?.self);
    // OUTPUT: "GET_SONG" 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文