'Mapped Types with one mandatory key from possible keys

The below code allows to create an oject that contains "k1" or "k2" or ("k1" and "k2") or none of them.

type Foo = "k1"|"k2";

type Bar = {[key in Foo]?: string};

const myObj1: Bar = { // ok

}

const myObj3: Bar = { // ok
    "k1": "random string",
    "k2": "random string",
}

My goal is to be able to have one and only one mandatory key, either "k1" or "k2".

So i want to be able to do the below:

const myObj1: Bar = { // Compile error

}

const myObj2: Bar = { // Compile error
    "k1": "random string",
    "k2": "random string",
}

const myObj3: Bar = { // ok
    "k1": "random string",
}

const myObj4: Bar = { // ok
    "k2": "random string",
}


Solution 1:[1]

Try this:

type Bar = {k1: string, k2?: never} | {k1?: never, k2: string};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Majed Badawi