0

I'm not sure if the title is correct.

But is there a way to not allow the union type, but make it more specific to only allow a specific interface?

See the following example:

interface Buz {
  buz: string;
}

interface Qux {
  qux: boolean;
}

export interface FooBar {
  content?: Buz | Qux;
}

const somethingBuz: FooBar = {
  content: {
    buz: 'yay!',
    qux: true // <- this should not be allowed
  }
}

const somethingQux: FooBar = {
  content: {
    buz: 'yay', // <- this should not be allowed
    qux: true
  }
}
Remi
  • 4,663
  • 11
  • 49
  • 84
  • TypeScript currently does not have exact types. See https://github.com/Microsoft/TypeScript/issues/12936. An object can always be augmented dynamically at runtime, which is why a TypeScript type means the value has *at least* the specified properties, but it may have more. – Jimmy Feb 15 '23 at 10:50
  • Your union is not discrimininated. It does not have a discriminant property that is of a literal type – Titian Cernicova-Dragomir Feb 15 '23 at 10:50
  • I don't agree that this is a duplicate. This is a different use-case since this is more about a _nested_ property. I have also found a potential answer which perhaps better explains the difference. – Remi Feb 15 '23 at 12:23
  • Omit & { content: Buz } – Remi Feb 16 '23 at 18:42

0 Answers0