This works (playground) though I am not sure whether providing the generic arguments of 'a' | 'b'
will suit your requirement or not.
interface Option<T> {
options: T[];
symbolOption: T;
}
// This will be OK:
const optionGood: Option<'a' | 'b'> = {
options: ['a', 'b'],
symbolOption: 'a' // ✅ OK
};
// But this will not be OK:
const optionBad: Option<'a' | 'b'> = {
options: ['a', 'b'],
symbolOption: 'c' // `c` is not included in the `options` list.
};
Here is another alternative courtesy of jcalz
(playground).
interface OptionConstraint<
T extends string,
O extends OptionConstraint<T, O>
> {
options: T[];
symbolOption: O["options"][number];
}
const asOption = <T extends string, O extends OptionConstraint<T, O>>(o: O) =>
o;
// This will be OK:
const optionGood = asOption({
options: ["a", "b"],
symbolOption: "a" // ✅ OK
});
// But this will not be OK:
const optionBad = asOption({
options: ["a", "b"],
symbolOption: "c" // `c` is not included in the `options` list.
});