2017-03-03 100 views
9
type someType = { 
    keyOne: string, 
    keyTwo: string, 
}; 

type someOtherType = { 
    keyOne: string, 
    keyTwo: string, 
    keyThree: string, 
}; 

這些類型的兩個創建的流類型是包含keyOnekeyTwo,唯一的區別是後者延伸前者與keyThree額外密鑰對象。流速:由延伸的另一類型

而不是編寫重複代碼,是否可以通過擴展someType來構建someOtherType流類型?在我看來,ES6對象休息/傳播浮現在腦海,但我不知道如何在Flow中完成這樣的事情。

謝謝!

+1

的可能的複製[流動型:類型繼承(A類型是B型的一個子集...)](http://stackoverflow.com/questions/42281539/flowtype-in​​heritance-of-types- type-a-is-a-subset-of-b) –

+0

很酷,感謝您的鏈接。 –

回答

10

你在找什麼是intersection type。根據文檔:

交集類型要求值爲所有輸入類型。

語法:路口:<類型1> & <類型2> ... & <鍵入n>

交叉型旨在擴展現有類型和添加其他類型的要求給它。

type someType = { 
    keyOne: string, 
    keyTwo: string 
} 

type someOtherType = someType & { 
    keyThree: string 
} 

const shouldBeOk: someOtherType = { 
    keyOne: 'biz', 
    keyTwo: 'buzz', 
    keyThree: 'baz', 
} 

const shouldError: someOtherType = { 
    keyOne: 123, 
    keyTwo: 'hello', 
    keyThree: 'world', 
} 

// flow error: 
16: const shouldError: someOtherType = { 
          ^object literal. This type is incompatible with 
8: type someOtherType = someType & { 
         ^object type 

交點類型的邏輯反義詞是union type。根據文檔:

聯合類型要求值爲輸入類型之一。

語法:Union:< type 1> | <類型2> ... | <類型n>

作爲一個例子。您可以使用聯合類型來創建一個枚舉類型。

type fooBarBazType = 'foo' | 'bar' | 'baz'; 
const shouldBeOk: fooBarBazType = 'bar'; 

const shouldError: fooBarBazType = 'buzz'; 

4: const shouldError: fooBarBazType = 'buzz'; 
            ^string. This type is incompatible with 
4: const shouldError: fooBarBazType = 'buzz'; 
        ^string enum 
+1

上述「可能重複」的答案已過時。相交類型[自2016年7月1日起實施](https://flowtype.org/blog/2016/07/01/New-Unions-Intersections.html)。 – thejohnbackes

+0

這不是過時的。在我的回答中,我提到交集類型。他們確實適用於大多數情況。但是,它們會導致出現奇怪的錯誤消息,並且在某些情況下它們不能按預期工作(例如,使用確切類型)。對象類型傳播將更好地實現此目的,事實上它只是在昨天登陸:https://github.com/facebook/flow/commit/ad443dc92879ae21705d4c61b942ba2f8ad61e4d –

+0

對不起Nat,我誤解了。我以爲你在說交叉口類型還沒有發佈。 – thejohnbackes