对象类型flowjs
说我有一个功能:对象类型flowjs
const example = (item : ?{+type?: ?string}) : {+result: ?string} => {
const state = {}
state.result = item.result
return state
}
这失败,给类型检查:
12: state.result = item.result
^^^^^^^ property `result`. Property not found in
12: state.result = item.result
^^^^^^ object type
为什么没有这种类型检测?我没有用确切的对象类型符号?{|+type?: ?string|}
来定义类型,所以它不应该允许其他键吗?那么确切的对象符号如何工作呢?我怎样才能定义这样的部分对象类型?这甚至有可能吗?
这听起来像你试图编码的参数item
可以有任何属性的类型。这听起来像一个地图,其流量与编码:
{ [key: KeyType]: ValueType };
你举的例子可以这样更新:
const example = (item : ?{[key: string]: string}) : {+result: ?string} => {
const state = {}
if(item)
{
state.result = item.result;
}
return state
}
注意,你必须做item
空校验,否则它不会typecheck,因为您在函数签名中声明了它为空。
如果有某些必需属性item
那么您可以使用交集类型来添加该约束。我将为此创建一个新类型,以便读取签名更容易:
type Item = {[key: string]: string} & {type: string}
const example = (item : ?Item) : {+result: ?string} => {
const state = {}
if(item)
{
state.result = item.result;
}
return state
}
example({type: 'blah', x: '2'}); // OK
example({'blah', x: '2'}); // Error: type is missing
是否有可能强制项目中的某些键的存在,如果存在? –
有一个问题,我仍然不太明白,回答是什么,如果不是这个,有用的确切对象符号是什么? –
确切的对象符号是这个部分:'{type:string}'。但我也使用'&'将它与地图类型结合起来说:它可以具有任何**字符串属性,但它必须具有'type'属性。 –
您的参数'item'没有名为'result'的属性。你是不是要编写'state.result = item.type'呢? (尽管你还需要在那里进行空检查)。 –
如果我的问题不清楚,请随时编辑。我的意思是这个对象中可能有很多键,并不是我可能会列举的所有键,我不明白为什么流没有使用“确切对象”符号来检查类型。任何方式,我可以澄清这个问题(随意编辑的方式!) –