我当时的印象是,只要在类型中声明的所有属性都存在,流中不精确的对象类型就可以被提供给具有未在该类型中声明的属性的对象。
流中的不精确对象类型声明表示“对象可以具有这些属性中的任何一个,加上任何未指定的属性”。因此,SubType类型的对象应该能够被分配为SuperType类型的对象,并且仍然是有效的。
我在这里错过了什么?
我相信这与嵌套对象类型有关,但是如果我不能修改genericPlan (SubType)上未声明的属性,这又有什么关系呢?
/* @flow */
type SuperType = {
plan: {
id: string,
location: {
id: string,
team: {
id: string,
},
},
},
};
type SubType = {
plan: {
id: string,
location: {
id: string,
},
},
};
const planWithTeam: SuperType = {
plan: {
id: '',
location: {
id: '',
team: {
id: '',
},
},
},
};
// The following throws this error:
// Cannot assign planWithTeam to genericPlan because property team is
// missing in SubType [1] but exists in SuperType [2] in property plan.location.
const genericPlan: SubType = planWithTeam;发布于 2019-07-17 09:12:58
不,嵌套对象支持在默认情况下是不变的。。要做协变,只需添加一个加号:
type SubType = {
+plan: {
id: string,
+location: {
id: string,
},
},
};https://stackoverflow.com/questions/57067162
复制相似问题