Reputation: 1814
I want to require a second type, if a first type (which is optional by itself) is set. Sometimes I have the problem in code, that with one optional property being set, other properties also need to be given for a react component to work.
Example
interface ComponentProps {
title: string;
isEnlarged?: boolean;
text?: string; // <-- If isEnlarged is set, text shouldn't be optional
imageUri?: string // <--- If isEnlarged is set, imageUri shouldn't be optional
}
The reason is to enforce consistent component behaviour through type checks. All enlarged components should have both a text and an image.
Is there a way to achieve that by TypeScript helper functions or logic?
Upvotes: 8
Views: 1715
Reputation: 250346
You can use a discriminated union:
type ComponentProps = {
title: string;
} & ({
isEnlarged: true; // asuming this must be true for otehrs to be required
text: string;
imageUri: string
} | {
isEnlarged?: false; // asuming this must be true for otehrs to be required
text?: string;
imageUri?: string
})
let a: ComponentProps = { title: "test" } //ok
let b: ComponentProps = { title: "test", isEnlarged: true } //err
let c: ComponentProps = { title: "test", isEnlarged: true, imageUri: "", text: "" } //ok
Upvotes: 13