我可以在Flow中向平面对象添加属性而不会出现任何错误。
但是如果我使用相同的模式向嵌套对象添加属性,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`.
答案 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
属性为只读。