我试图定义一个类型,其中一个字段只有在有另一个字段(可选)时才为必填字段。 我尝试了一个非常简单的案例,但我不明白为什么它不起作用。 我还注意到 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' }
为什么最后一行没有引发错误?