簡體   English   中英

FlowType:數組對通用參數的形狀過於嚴格

[英]FlowType: Array is too strict about the generic parameter's shape

為什么流對數組元素的形狀如此嚴格。 當它是單個對象時,它很酷,但是數組卻以某種方式不令人滿意。 是否可以使其以某種方式工作?

function foo1(x: { a: string, b: number }) {
  foo2(x) // all cool, no errors
}
function foo2(x: { a: string }) {
}

function foo3(x: Array<{ a: string, b: number }>) {
  foo4(x)  // error, see below
}
function foo4(x: Array<{ a: string }>) {
}

// 錯誤信息

foo4(x)
     ^ Cannot call `foo4` with `x` bound to `x` because property `b` is missing in object type [1] but exists in object type [2] in array element.
References:
12: function foo4(x: Array<{ a: string }>) {
                           ^ [1]
9: function foo3(x: Array<{ a: string, b: number }>) {

https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVUCuA7AxgFwEs5swo44BGACgA8AuMAbzAENGBnfAJ0OwHMANGABGjbJgC2IgKbcwAXwCUzVGDIUATHSWoFGHAWKlycbQ2ZtOPPv0Uqme9FjxESGuAGY6jAILduVgBPAB4WdjAuXgFhMTAJaTlFAD4HNQ8AFh0nFyN3UyyLf0DQ8OtouwVU1QUgA

編輯:

我找到了一種使用$ Subtype <>使其工作的方法,但是我仍然不明白為什么上面的代碼不起作用,因此歡迎大家回答。

function foo3(x: Array<{ a: string, b: number }>) {
  foo4(x)
}

function foo4(x: Array<$Subtype<{ a: string }>>) {
}

因此,答案是函數foo4可以修改數組並推入{ a: 'foo' } ,但是它將違反原始數組的類型,即{ a: string, b: number }

因此正確的解決方案是使用

function foo4(x: $ReadOnlyArray<{ a: string }>) {
}

在這種情況下, foo4不能使數組變異,所以我們很安全

感謝Ryan Cavanaugh指出問題評論中的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM