Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Typescript Interface to contain a non-mandatory property or another

I know that there are similar questions here but mine is a little different.

There is an Interface that can have one or another property, let's call them black and white they aren't mandatory, so the Interface is valid without them and it is valid with one of them.

Good:

interface MyInterface {
  name: string;
}

Good:

interface MyInterface {
  name: string;
  black?: boolean;
}

Good:

interface MyInterface {
  name: string;
  white?: boolean;
}

Bad: (or it could be Good if we can check that maximum one of either black or white is there)

interface MyInterface {
  name: string;
  black?: boolean;
  white?: boolean;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Because TypeScript is structurally-typed, it is not an error for an object to have excess properties, unless you explicitly disallow this by setting the property's optional type to never, like this:

TS Playground

type BlackOptional = {
  black?: boolean;
  white?: never;
};

type WhiteOptional = {
  black?: never;
  white?: boolean;
};

type Name = {
  name: string;
}

type Example = (Name & BlackOptional) | (Name & WhiteOptional);

const example1: Example = { /*
      ^^^^^^^^
Types of property 'black' are incompatible. Type 'boolean' is not assignable to type 'never'.(2322) */
  name: 'name',
  black: true,
  white: true,
};

const example2: Example = {
  name: 'name',
  black: true,
};

const example3: Example = {
  name: 'name',
  white: true,
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!