'Mapped types: Make property required based on whether array of same object contains string literal
Is it possible to make an object property dependent on whether an array of the same object contains a string literal?
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
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
