Home > front end >  Typescript. Can I define conditional types?
Typescript. Can I define conditional types?

Time:02-10

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related