mouchin777
mouchin777

Reputation: 1588

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?

Upvotes: 2

Views: 39

Answers (2)

Gordon
Gordon

Reputation: 4843

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

Upvotes: 2

pzaenger
pzaenger

Reputation: 11974

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.

Upvotes: 0

Related Questions