在Flow中向嵌套对象添加属性会导致错误

时间:2018-03-26 22:45:43

标签: reactjs flowtype

我可以在Flow中向平面对象添加属性而不会出现任何错误。

View demo

但是如果我使用相同的模式向嵌套对象添加属性,Flow会抛出错误:

/* @flow */

type Content = {
    fields: {
        slug: string,
    },
    frontmatter: {
        title: string,
    }   
};

type CustomContent = {
    fields: {
      slug: string,
    },
    frontmatter: {
        title: string,
        // This is the new property:
        headerImage: string,
    }
};

function doSomethingWithContent(content: Content) {
    return [
        content.fields.slug,
        content.frontmatter.title,
    ];
}

function doSomethingWithCustomContent(content: CustomContent) {
    return [
        content.fields.slug,
        content.frontmatter.title,
        content.frontmatter.headerImage,
    ];
}

错误:

doSomethingWithContent(customContent);
                           ^ Cannot call `doSomethingWithContent` with `customContent` bound to `content` because property `headerImage` is missing in object type [1] but exists in object type [2] in property `frontmatter`.

View demo

1 个答案:

答案 0 :(得分:1)

为此,frontmatter属性需要标记为covariant,例如

type Content = {
    fields: {
        slug: string,
    },
    frontmatter: {
        title: string,
    }   
};

type Content = {
    fields: {
        slug: string,
    },
    +frontmatter: { // Note the "+" prefix here
        title: string,
    }   
};

如果Flow 没有错误,那么你的功能完全有效

function doSomethingWithContent(content: Content) {
  content.frontmatter = { title: "" };

使content的类型仍然是有效的Content,但是无效的CustomContent对象。通过标记属性协变,它实质上使frontmatter属性为只读。