将流类型 SuperType 的对象分配给 SubType 会导致错误

Assigning an object of flow type SuperType to SubType causes error

我的印象是,只要 中声明了所有属性,就可以为 Flow 中的不精确对象类型提供一个具有未在该类型中声明的属性的对象类型存在。

Flow 中不准确的对象类型声明表明 "the object can have any of these properties, plus any more unspecified"。因此,一个 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;

不,nested object props are invariant by default。要进行协变,只需添加一个加号:

type SubType = {
  +plan: {
    id: string,
    +location: {
      id: string,
    },
  },
};

Try