Chris A
Chris A

Reputation: 1100

Only allow a certain set of strings as keys in interface

I would like to be able to change the below so that the nested object can only have a certain set of keys, let's say foo or bar, and allows, but does not require, all of the set.

interface ConfigObject {
    [key:string]: {
        [key:string]:string
        // this compiles, and allows any number of keys (good), but allows any string as the key (bad)
    }
}

I tried changing to

interface ConfigObject {
    [key:string]: {
        "foo"|"bar":string
    }
}

but this fails to compile as a syntax error, also tried putting in an array, parentheses. A single string works but not multiple.

I can do:

interface ConfigObject {
    [key:string]: {
        [K in "foo"|"bar"]:string
    }
}

(https://stackoverflow.com/a/51659490/8940624)

But this makes foo AND bar required, so a nested object with only foo or only bar will fail.

Upvotes: 3

Views: 1126

Answers (1)

superhawk610
superhawk610

Reputation: 2663

Your last implementation was close, you just need to mark the properties as optional using the ? operator:

interface ConfigObject {
    [key: string]: {
        [key in "foo" | "bar"]?: string;
    };
}

Upvotes: 3

Related Questions