Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript. Can I define conditional types?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading