定义类型时,我们可以根据另一个属性来创建一个属性吗?
一个例子是:
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
。
关于Typescript - 基于另一个属性的条件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59350724/