为什么会失败?

时间:2018-07-17 20:22:50

标签: flowtype

实时示例here

type Activity = {
  verb: string
}

type CommentActivity = {
  verb: 'comment'
}

function doStuff (activity: Activity) {}

const commentActivity: CommentActivity = { verb: 'comment' }
const likeActivity: Activity = { verb: 'like' }

doStuff(likeActivity)
doStuff(commentActivity)

失败:

15: doStuff(commentActivity)
            ^ Cannot call `doStuff` with `commentActivity` bound to `activity` because string literal `comment` [1] is incompatible with string [2] in property `verb`.
References:
6:   verb: 'comment'           ^ [1]
2:   verb: string           ^ [2]

错误消息很清楚,我知道如何解决此问题,但是我不明白为什么字符串文字不被视为有效字符串?

1 个答案:

答案 0 :(得分:2)

这是属性差异的问题。如果您有类似doStuff的函数,且类型为

(activity: Activity): void => {}

然后该函数完全有效

function doStuff (activity: Activity) {
    activity.verb = "some new verb";
}

,然后100%进行类型检查。这意味着如果

doStuff(commentActivity)

被允许,doStuff实际上会更改commentActivity的类型,这就是为什么这会为您引发错误。

您需要做的是告诉Flow您不会更改.verb的值,实际上是使其在doStuff内部为只读。为此,请在属性名称前放置一个+

type Activity = {
  +verb: string
};

On Flow/try