Home > front end >  typescript only allow circular reference keys from the same object
typescript only allow circular reference keys from the same object

Time:02-01

I have an object that describes service definitions. Each service definition may "inject" other service definitions through the optional dependencies object.

How can I only allow keys that exist within this object? For example, in the screenshot below, I've defined the service "viewport" which I inject in "clock". Intellisense/autocomplete should only show "viewport".

Is this even possible?

enter image description here

So in the example above, I would only expect "clock" and "viewport" to appear as possible options for the "dependencies" array. I know clock shouldn't be able to inject itself, but I'm okay with that.

CodePudding user response:

You could create a generic function to create the config, since it infers the types

function createConfiguration<T extends ContainerConfiguration<R>, R extends keyof T>(config: T) {
    return config
}

And update your types to take generic arguments

type ContainerConfiguration<T extends string | number | symbol = any> = {
    [P in T]: ServiceDefinition<Exclude<T,P>>
}
type ServiceDefinition<T> = {
    class: new (...args: any[]) => any;
    dependencies?: T[]
}

Playground Link

  •  Tags:  
  • Related