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

Dependent Disjoint Unions in Typescript

Given a simple Record<string, Record<string, any>> defined as a constant record of possible named configurations, I want a type which dynamically restricts the configuration type based on the key. Consider the following example:

const configs = {
    "fooConfig": {c: "s"},
    "barConfig": {c: 1, b: 2}    
} as const;

type ConfigDef<k extends keyof typeof configs = keyof typeof configs> = {
    a: k,
    v: typeof configs[k]
}

const x: ConfigDef = {
    a: "fooConfig",
    v: {c: 1, b: 2} // this should not work
}

Crucially, for the type ConfigDef, I need the user to be able to use the type implicitly without passing in the actual key of the config as the generic type (i.e. they should not need to use the explicit syntax const x: ConfigDef<"fooConfig">). Is this possible, and if so, how?

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

>Solution :

If you want to refer to ConfigDef as a specific (non-generic) type, then it should evaluate to the union of your original ConfigDeg<K> for each K in keyof typeof configs. That is, you need to distribute ConfigDef<K> across the union keyof typeof configs. One way to do this is to write a distributive object type as coined in microsoft/TypeScript#47109:

type ConfigDef = { [K in keyof typeof configs]: {
    a: K,
    v: typeof configs[K]
} }[keyof typeof configs]

That evaluates to

/* type ConfigDef = {
    a: "fooConfig";
    v: {
        readonly c: "s";
    };
} | {
    a: "barConfig";
    v: {
        readonly c: 1;
        readonly b: 2;
    };
} */

and therefore gives you the behavior you want:

const x: ConfigDef = {
    a: "fooConfig",
    v: { c: 1, b: 2 } // error!
}

A distributive object type is when you immediately index into a mapped type. The general form is {[K in KS]: F<K>}[KS], where KS is a keylike type. In your case, we have KS being keyof typeof configs and F<K> as your original ConfigDef<K>.

Playground link to code

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