TypeScript - using recursive generics properly

53 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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"