定义类型时,我们可以根据另一个属性来使一个属性成为必需的吗?
一个例子是:
type Parent = {
children?: Child[];
childrenIdSequence: string[]; // Only make this required when `children` is given
}
您想要的可以使用联合类型来实现:
type Parent = {
children: Child[],
childrenIdSequence: string[]
} | {
children: undefined
}
这意味着一个Parent
要么有一个children
数组和一个childrenIdSequence
数组,或其children
属性未定义,并且不保证具有childrenIdSequence
大批。该类型可以通过测试来缩小控制流范围children
财产:
function test(p: Parent): void {
if(p.children) {
// p: { children: Child[], childrenIdSequence: string[] }, so OK
console.log(p.childrenIdSequence);
} else {
// p: { children: undefined }, so type error
console.log(p.childrenIdSequence);
}
}
然而,有一点缺点:children
即使您希望未定义属性,属性也是必需的。你必须明确地写一个像这样的文字{ children: undefined }
而不是仅仅{}
,否则它不会是类型Parent
.
如果您尝试使用声明类型children?: undefined
作为可选属性,那么联合将不起作用,因为一个分支是另一个分支的结构子类型,并且函数中的类型将无用地缩小为p: never
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)