I have a starting type called BaseType
, and I am looking to dynamically extend it by combining multiple types based on a discriminating value. For example, if the discriminating value is set to "foo" or "bar", I would create separate types like FooType and BarType with specific properties.
Essentially, I want the flexibility to discriminate between various types as needed.
For instance:
interface BaseType {
base: string;
}
interface FooType {
foo: boolean;
fooType: string;
}
interface BarType {
bar: boolean;
barType: number;
}
interface BazType {
baz: boolean;
bazType: boolean;
}
// The following examples are valid only when discriminating to one type.
myFunc({
base: "",
foo: true,
fooType: "", // <== An error should occur if this is missing.
});
myFunc({
base: "",
bar: true,
barType: 2, // <== An error should occur if this is missing.
});
// However, I aim to discriminate among multiple types using a similar approach.
myFunc({
base: "",
foo: true,
fooType: "", // <== Error if missing when foo is true.
bar: true,
barType: 2, // <== Error if missing when bar is true.
});
// Another scenario
myFunc({
base: "",
bar: true,
barType: "", // <== Error if missing when bar is true.
baz: true,
bazType: false, // <== Error if missing when baz is specified.
});
// This can exclusively discriminate to only one type at a time, not both simultaneously.
type AllType = FooType | BarType | BazType;