2

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?

mouchin777
  • 1,428
  • 1
  • 31
  • 59

2 Answers2

2

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'
}

Playground example

Gordon
  • 4,823
  • 4
  • 38
  • 55
0

Keep it simple: merge them as required properties in a separate optional object:

type BannerConditions = {
  type: string;
  resource?: {
    publication_id: number;
    product_id: number;
    type: string;
  };
};

I changed resource to type since resource.resource seems to be a bit odd. BannerConditions could also be an interface rather than a type.

pzaenger
  • 11,381
  • 3
  • 45
  • 46