Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript only allow circular reference keys from the same object

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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<T>
}
type ServiceDefinition<T> = {
    class: new (...args: any[]) => any;
    dependencies?: T[]
}

Playground Link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading