1

I am trying to define a type where a field is mandatory only if there is another field (that is optional). I have tried a very simple case, but I can't understand why it doesn't work. I have noticed also that the same solution was suggested in this post.

interface A {
  address: string
  data?: string
}

interface B extends A {
  nonce: number
  callbackAddress?: string
}

export type Configuration = string | A | B

const conf: B = {
    address: '',
    callbackAddress: '',
    nonce: 1 // if I try to remove this field, I get an error.
}

// this is the complete interface
const conf2: Configuration = { address: '', nonce: 123, callbackAddress: '0x' }

// I expect 'nonce' to be required here
const conf1: Configuration = { address: '', callbackAddress: '0x' }

Why doesn't the last line raise an error?

  • [Here](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgILIN4ChnLgE3yggGcSAuZEsKUAcx2XzjDgH5LraQGBfLLKEixEKAELIIAD0gh8JNJkYgA9iCSUQAVwC2AI2iMEcADYm9iANapCxMhyo16WflmkAHFVDDIwAT3cUAGE1GGA6LSgWYDVkAF5HbjpkAB9FNLEBBDVqZGyQGEoJBOxcXAIiUgpkAHIagBpGXGMzCwRrWyrKOsay5FV1CEoARmQAejHkYBhkAElfKD9fFWRiHRUANxQwAAtgBTCIE3x6ueQ6CB84EEkoKC8AOhcBCd89hX23lGyddxNLlBCaDwJBYfK5fIwABMlBCBXCkWisRKeE6ZG6DX6ag0yGGUIAzKcWuYrDZKujagAGKQ1ZCuV7zDwQBA+GoDJC0sArAyrCAARy0wGI+GQO2gEDBOR8kOGsNCCKiYBiNxRFTs1R6eVMJPaZPV3WptP4QA) a ts playground. – Antonio Morrone May 12 '21 at 09:28
  • https://github.com/microsoft/TypeScript/issues/12745 – Roberto Zvjerković May 12 '21 at 09:36
  • https://stackoverflow.com/questions/46370222/typescript-a-b-allows-combination-of-both – Roberto Zvjerković May 12 '21 at 09:40
  • @RobertoZvjerković thanks for pointing out. I have just notice there is an open bug https://github.com/microsoft/TypeScript/issues/20060 – Antonio Morrone May 12 '21 at 09:43

0 Answers0