TypeScript - 正确使用递归泛型
我正在尝试以一种可以从编辑器获得很多帮助的方式使用递归泛型。
这是一个例子:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
现在您可以在 TypeScript 中使用可选链来简化,如下所示。这样打字稿编译器就会期望 NULL |欠款
Now you can use Optional chaining in TypeScript simplify as shown below. So that typescript compiler will expect NULL | underfined