In my code, I have a custom type defined like this (but it's not working):
type MyType =
| {
foo: string;
}
| {
foo: string;
barPre: string;
barPost: string;
}
| {
foo: string;
quxPre: string;
quxPost: string;
}
| {
foo: string;
barPre: string;
barPost: string;
quxPre: string;
quxPost: string;
};
I need objects to fit the structure of MyType
as follows:
const myThing1: MyType = { foo: 'foo' };
const myThing2: MyType = { foo: 'foo', barPre: 'barPre', barPost: 'barPost' };
const myThing3: MyType = { foo: 'foo', quxPre: 'quxPre', quxPost: 'quxPost' };
const myThing4: MyType = {
foo: 'foo',
barPre: 'barPre',
barPost: 'barPost',
quxPre: 'quxPre',
quxPost: 'quxPost',
};
Objects that do not conform to these rules are considered invalid MyType
s:
const myThing5: MyType = {}; // missing 'foo'
const myThing6: MyType = { barPre: 'barPre', barPost: 'barPost' }; // missing 'foo'
const myThing7: MyType = { foo: 'foo', barPre: 'barPre' }; // if `barPre` exists, so must `barPost`
const myThing8: MyType = { barPre: 'barPre', barPost: 'barPost', quxPre: 'quxPre', quxPost: 'quxPost' }
I managed to get the correct type by defining it in a more complex way:
type MyType = {
foo: string;
} & ({
barPre?: undefined;
barPost?: undefined;
} | {
barPre: string;
barPost: string;
}) & ({
quxPre?: undefined;
quxPost?: undefined;
} | {
quxPre: string;
quxPost: string;
});
However, this approach seems cumbersome. Is there a simpler method to achieve the same result?