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?

2
  • 1
    Because TS has structural type system, you need to use extra type utility helper to handle this kind of union type. See example and great answer with explanation Commented Feb 10, 2022 at 11:28
  • I'd willing to bet that this question is a duplicate. Are you agree ? Commented Feb 10, 2022 at 11:29

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.