Home > front end >  restrict keys of inner object based on starts with on key of outer object
restrict keys of inner object based on starts with on key of outer object

Time:09-29

I have two string literals and created an interface based on those string literals as follows:

type context = 'a' | 'b';

type statusKey = 'aTest' | 'aFinal' | 'bTest' | 'cTest'

interface State {
    status: {
        [c in context]: {
            [key in statusKey]: {
                seen: number;
                total: number;
            }
        }
    }
}

Now, I want to restrict the inner object's keys such that: it should only allow keys that starts with key of its parent object.

So, as per my example, the valid status object should be:

    a: { 
        aTest: {
            seen: number;
            total: number;
        };
        aFinal: {
            seen: number;
            total: number;
        };
    };
    b: {
        bTest: {
            seen: number;
            total: number;
        };
    };

So, inshort a should not allow keys that does not start with a and b should not allow keys that does not start with b.

CodePudding user response:

The Extract utility type will help us to extract every string literal from statusKey which is assignable to the template literal type ${C}{string}.

interface State {
    status: {
        [C in context]: {
            [Key in Extract<statusKey, `${C}${string}`>]: {
                seen: number;
                total: number;
            }
        }
    }
}

Playground

  • Related