In typescript, I need a type called C, with fields A and B (both string), and C, a boolean. Where B is required if C is true, and hidden if it is not.
In TypeScript, you can create a type called C with the fields A and B (both strings), and C (a boolean) using the following syntax:
type C = {
A: string;
B?: string; // the '?' indicates that this field is optional
C: boolean;
}
To specify that B is required if C is true, you can use an intersection type and a type guard:
type C = {
A: string;
C: boolean;
} & (
{ // this type is only valid if C is true
B: string;
}
);
function isCWithB(c: C): c is C {
return c.C && c.B !== undefined;
}
Then, you can use the isCWithB function as a type guard to narrow the type of the C object and access the B field safely:
const c: C = {
A: 'foo',
C: true,
B: 'bar'
};
if (isCWithB(c)) {
// here, the type of c is narrowed to {A: string; C: boolean; B: string}
console.log(c.B); // outputs 'bar'
}
Keep in mind that this solution only works if the B field is optional in the C type, otherwise TypeScript will raise an error when you try to use the B field in the type guard.