[英]flowType for destructuring Function's parameters with default values
Do we have any workaround in this situation that does not break type checking? 在这种情况下,我们有没有不破坏类型检查的解决方法?
// Error
function foo({name = 42}: {name: ?number}) {
// ^ null or undefined [1] is incompatible with number [2].
console.log(name);
}
The solution from the bug prevent flow from checking default value type. 该错误的解决方案阻止流程检查默认值类型。
// Correct
const foo = ({name = true}: $Subtype<{name: ?string}>) => {
// ^ flow does not check this
console.log(name);
}
The only workaround that also maintains type safety, is to not use destructuring: 还能保持类型安全的唯一解决方法是不使用解构:
function foo(props: {name: ?number}) {
let name = props.name === undefined ? 41 : props.name;
console.log(name);
}
We have an old code base for adding a types, so we want not to change the functionality. 我们具有用于添加类型的旧代码库,因此我们不希望更改功能。
Destructuring argument in the body instead of header - works great for me. 分解参数而不是标题中的内容-对我来说很棒。
function foo(arg: {name: ?number}) {
const { name = 42 } = arg;
// the default value is only used for undefined values.
console.log((name: (number | null)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.