Imagine I have the following type
type BannerConditions = {
publication_id?: number;
product_id?: number;
resource?: string;
type: string;
};
But publication_id and product_id can only exist if resource exists. Can I define it somehow?
>Solution :
You could use a union to describe the two type
type BannerConditions = {
publication_id: number;
product_id: number;
resource: string;
type: string;
} | {
publication_id: undefined;
product_id: undefined;
resource: undefined;
type: string;
}
// foo would throw an error
const foo: BannerConditions = {
publication_id: 1,
product_id: 2,
resource: undefined,
type: 'x'
}
// no error for bar
const bar: BannerConditions = {
publication_id: 1,
product_id: 2,
resource: 'test',
type: 'x'
}