gpt4 book ai didi

flowtype - 如何指定 Flowjs 中所需的两个 Prop 之一?

转载 作者:行者123 更新时间:2023-12-04 18:03:03 24 4
gpt4 key购买 nike

我有各种 React 组件,当传入不同的 props 时,它们可以具有不同的功能。我经常遇到一些分支逻辑,其中 if prop1存在,做一件事,但如果 prop2在场做别的事情。

一个例子可能是一个元素的两个更改处理程序,其输入采用不同的参数。

有没有办法在 Flowjs 中指定需要两个处理程序之一?

最佳答案

幸运的是,您想要的 Flow 类型注释可以应用于 React 之外的上下文。一般来说,如果你想要一个异或类型检查,你可以这样做:

type Something = {
prop1: number,
prop2?: null
}

type Another = {
prop1?: null,
prop2: number
}

function foo(parameter: Something | Another) {

}

foo({ prop1: 10 }); // Good
foo({ prop2: 10 }); // Good
foo({ prop1: 10, prop2: 10 }); // Bad

如果你想要一个包含或类型检查,你可以这样做:
type Something = {
prop1: number,
prop2?: null
}

type Another = {
prop1?: null,
prop2: number
}

type SomethingAndAnother = {
prop1: number,
prop2: number
}

function foo(parameter: Something | Another | SomethingAndAnother) {

}

foo({ something: 10, prop1: 10 }); // Good
foo({ something: 10 }); // Bad
foo({ prop1: 10 }); // Good
foo({ prop2: 10 }); // Good
foo({ prop1: 10, prop2: 10 }); // Good

在 React 中,您可以在 props 上定义类型属性(property),像这样:
class TodoList extends React.Component {
props: Something | Another;

render(): React.Element {
return (
// ....
)
}
}

关于flowtype - 如何指定 Flowjs 中所需的两个 Prop 之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com