這裏是不工作我期望它的方式簡單的有界多態性例如:
// @flow
function thisBreaks<T: 'a' | 'b'>(x: T): T {
if (x === 'a') {
return 'a'
} else {
return 'b'
}
}
function thisWorks<T: 'a' | 'b'>(x: T): T {
return x
}
const a = 'a'
const aPrime: 'a' = thisWorks(a)
const b = 'b'
const bPrime: 'b' = thisWorks(b)
5: return 'a'
^string. This type is incompatible with the expected return type of
3: function thisBreaks<T: 'a' | 'b'>(x: T): T {
^some incompatible instantiation of `T`
7: return 'b'
^string. This type is incompatible with the expected return type of
3: function thisBreaks<T: 'a' | 'b'>(x: T): T {
^some incompatible instantiation of `T`
我本來期望的第一個例子來工作,因爲如x === 'a'
支票可能會提煉T
至'a'
,對不對?
雖然這是不可能的,但你可能能夠完成你想要做的功能交叉點。我創建了一個工作類型爲你的函數:[嘗試流鏈路(https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVBjOA7AzgFzCjjgC4wAKCgD3IHIBDOgSjAF4A+MRl1MfgQIBklGvQBGLdlzqTmqNqOrSwytuu5MwAfk10wEluQbYAnvMw4CYcQwBO9LYuJwKPeVjyFbAL0PsiEjc5Sy8iBgBLGFxHfWcg2V4gA) – Andy