我想将类型定义为两个接口的联合.两个接口中的一个应该是可选的,这意味着联合类型应该具有可选接口的all or none个属性.现在应该允许联合类型仅包括可选接口的属性子集.
也就是说,大概是这样的:
interface A {
a1: string
a2: string
}
interface B {
b1: string
b2: string
}
type C = A | (A & B)
然而,这并不是quite%的工作,如我所期望的.
- 禁止部分包含接口A属性,例如
const c: C = {
// a1: 'a1',
a2: 'a2',
b1: 'b1',
b2: 'b2',
}
导致此错误,如预期的那样:"类型‘{a2:字符串;b1:字符串;b2:字符串;}’中缺少属性‘a1’."
- 但是,允许部分包含接口B的属性,例如
const c: C = {
a1: 'a1',
a2: 'a2',
// b1: 'b1',
b2: 'b2',
}
不会导致错误.
What am I missing? How can I "fix" my types to achieve what I want?个
我试过的其他 Select
type C = A & (B | {}) // Same as above.
type C = A & (B | undefined) // This catches { a1: 'a1', a2: 'a2', b2: 'b2' }, but doesn't allow for { a1: 'a1', a2: 'a2' }, i.e. it requires the union to have all of the interface B properties always.