Infer type of an object property based on object's sibling keys

Issue

Consider these array of objects:

  const inputGroup = [
{
    key: "primary_category",
    label: "Primary Category",
    elType: "select",
    elementConfig: {
      options: categories,
    },
  },
  {
    key: "extra_tags",
    label: "Extra tags",,
    elType: "input",
    elementConfig: {
      type: "text",
      placeholder: "e.g. startup, analytics, svelte, seo, social media,",
    },
  },
]

How would I type this so that elementConfig‘s allowed properties depend on elType‘s value?

Solution

You can define a type that has the base properties (key, label) and intersect it with a union of two object types, one with elType: "select" and the relevant type for elementConfig for selects, and another with elType: "text" and the relevant type for elementConfig for text fields, like this:

type GroupEntry =
    {
        key: string;
        label: string;
    } & (
        {
            elType: "select",
            elementConfig: {
                options: string; // Or whatever the type of `categories` should be
            }
        } |
        {
            elType: "input",
            elementConfig: {
                type: string; // Or maybe "text" | "number" | ...
                placeholder?: string;
            }
        }
    )
;

Then you declare your array of that type:

const inputGroup: GroupEntry[] = [
    {
        key: "primary_category",
        label: "Primary Category",
        elType: "select",
        elementConfig: {
            options: "categories",
        },
    },
    {
        key: "extra_tags",
        label: "Extra tags",
        elType: "input",
        elementConfig: {
            type: "text",
            placeholder: "e.g. startup, analytics, svelte, seo, social media,",
        },
    },
    {
        key: "something",
        label: "stuff",
        elType: "select",
        elementConfig: {
            type: "text" // <==== Error as desired
        }
    }
];

Playground link

Answered By – T.J. Crowder

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published