我正在尝试基于对象中的嵌套属性创建联合类型。请参见下面的示例:
type Foo = {
abilities: {
canManage: boolean
}
}
type Bar = {
abilities: {
canManage: boolean
}
extraProp: number
}
type Condition1 = {
abilities: {
canManage: true
}
} & Bar
type Condition2 = {
abilities: {
canManage: false
}
} & Foo
type TotalData = Condition1 | Condition2
const data: TotalData = {
abilities: {
canManage: false, // if canManage is false, TS should complain when I add the `extraProp` key
},
extraProp: 5
}
我遇到的问题是 TypeScript 忽略了我设置的条件。如果 canManage 值为 true,我只想允许特定的属性。但是当嵌套时似乎无法正常工作。但如果没有嵌套,只有简单的内容,那就没问题:
type Foo = {
canManage: boolean
}
type Bar = {
canManage: boolean
extraProp: number
}
type Condition1 = {
canManage: true
} & Bar
type Condition2 = {
canManage: false
} & Foo
]
type TotalData = Condition1 | Condition2
const data: TotalData = {
canManage: false,
extraProp: 5 // now typescript complains that this property shouldn't be here because canManage is false
}
当尝试基于嵌套对象内的属性设置联合时,我该如何解决此问题?
type Foo = { abilities: { canManage: boolean }; extraProp?: never }
符合你的需求吗?只有在特定情况下才禁止使用额外的属性,而这似乎不是其中之一。如果这适合您,我会写出一个答案;如果不行,请解释一下哪个地方不符合您的用例。祝好运! - jcalz