2016-08-02 40 views
1

一個字符串,我可以接受一個數組或一個字符串的函數:允許函數接受一個數組或流

/* @flow */ 
type Product = Array<string> | string 

function printProducts(product: Product) { 
    if (product.constructor === 'array') { 
     product.map(p => console.log(p)) 
    } else { 
     console.log(product) 
    } 
} 

流量抱怨「屬性Map沒有找到字符串」。我如何改變我的類型定義來滿足這個?支持dynamic type tests

回答

3

使用一個,在這種情況下Array.isArray

/* @flow */ 
type Product = Array<string> | string 

function printProducts(product: Product) { 
    if (Array.isArray(product)) { 
     product.map(p => console.log(p)) 
    } else { 
     console.log(product) 
    } 
} 
相關問題