TypeScript definition for a JSON object based on other entry in the JSON object

  Kiến thức lập trình

I have a JSON object I’m writing a TypeScript definition for. In this object I would like to enumerate the components. At this time the components property is an array of strings. It’s unrestricted but I would like to add an overrides property where entries from the components array can have prop overrides specified.

Is there a way to restrict the componentName key in the overrides object to match one of the entries in the components array? Currently I have it set like this:

interface MyJsonObject {
    components: string[];
    overrides: {
        [componentName: string]: {
             [propName: string]: unknown;
        };
    };
}

But I would like to validate that this is valid:

const config: MyJsonObject = {
    components: ['test'],
    overrides: {
        test: {
            foo: 'bar',
        }
    }
}

And that this is invalid

const config: MyJsonObject = {
    components: ['test'],
    overrides: {
        baz: {
            foo: 'bar',
        }
    }
}

LEAVE A COMMENT