首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将流类型为SuperType的对象分配给SubType会导致错误

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

Stack Overflow用户
提问于 2019-07-17 00:52:42
回答 1查看 232关注 0票数 2

我当时的印象是,只要在类型中声明的所有属性都存在,流中不精确的对象类型就可以被提供给具有未在该类型中声明的属性的对象。

流中的不精确对象类型声明表示“对象可以具有这些属性中的任何一个,加上任何未指定的属性”。因此,SubType类型的对象应该能够被分配为SuperType类型的对象,并且仍然是有效的。

我在这里错过了什么?

我相信这与嵌套对象类型有关,但是如果我不能修改genericPlan (SubType)上未声明的属性,这又有什么关系呢?

代码语言:javascript
复制
/* @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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-17 09:12:58

不,嵌套对象支持在默认情况下是不变的。。要做协变,只需添加一个加号:

代码语言:javascript
复制
type SubType = {
  +plan: {
    id: string,
    +location: {
      id: string,
    },
  },
};

试一试

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57067162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档