Allyl Isocyanate
Allyl Isocyanate

Reputation: 13616

Allowing a function to accept an array or a string in Flow

I have a function that can accept an array or a string:

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

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

Flow complains "property Map not found in String". How can I change my type definition to satisfy this?

Upvotes: 1

Views: 70

Answers (1)

Ross Allen
Ross Allen

Reputation: 44880

Use one of the supported dynamic type tests, in this case 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)
    }
}

Upvotes: 3

Related Questions