[英]Is it possible to cast an Object to an exact type in Flow?
I'm wondering how one might go about casting an Object
to a user defined exact type in Flow. 我想知道如何将Object
转换为Flow中用户定义的确切类型。 For example: 例如:
//@flow
type exactType = {|x : number|}
function test(a : Object) : exactType {
if(typeof(a.x) === 'string'){
return (a : exactType);
}
throw new Error('Incorrect type!')
}
Is it even possible to write such a function? 甚至可以编写这样的功能吗? Ie is it possible to convice the type checker that parameter a
has only a single field named x
with type number
? 即是否可以建议类型检查器确定参数a
仅具有一个名为x
且具有类型number
字段?
There is no safe way to do this. 没有安全的方法可以执行此操作。 However, you can always cast through any
to circumvent the typechecker: 但是,您始终可以强制执行any
来规避类型检查器:
return ((a: any): exactType);
Ideally, you would refactor your code to avoid using Object
, since it's an unsafe type. 理想情况下,您应该重构代码以避免使用Object
,因为它是不安全的类型。 However, if that's not possible the best you can do is to carefully circumvent the typechecker like this. 但是,如果不可能的话,您最好的办法就是仔细地规避类型检查器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.