Can an object property be set to required or optional based on the presence of a specific string in an array within the same object?
type Operator = "A" | "B"
type SomeStruct = {
operators: Operator[];
someProp: string; // this should be required if operators include "A", optional if not
}
// desired result
const structWithA: SomeStruct = {
operators: ["A", "B"],
someProp: "" // correct, since operators contains "A", someProp is required
};
const structWithB: SomeStruct = {
operators: ["B"],
// currently errors, but desired outcome is that it should not error, since operators does not contain "A"
};
declare const structs: SomeStruct[];
structs.map(struct => {
if(struct.operators.includes("A")) {
// someProp is safely accessible
}
// since .includes has a narrow type signature, maybe another way to safely access someProp is needed
})