Search code examples
flowtypeflow-typed

Encaps string in flow


I created this flow demo - https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVBjOA7AzgFzAEEwBeMACgEMN8BLHAFQE8AHAUwC4wCAnO7AHMAlGQB8YAOQBhAPIBVAHKMAogCUA+pLABqMDXpM27MMGDFaDbCw4AFXuyh0AHu17oseQgCEYVABZkxAAGAEZ+-sEA3EA

I am using React Native and Flow.

My code is:

const A = (actionType: string) => 'COUNTER_' + actionType // ActionTypePrefixer
const UP = A`UP`;

My goal is to call a function with backticks.Flow highlights this as an error saying:

Is there any way to do encaps with:

[flow] array (This type is incompatible with the expected param type of string See also: encaps tag)

Screenshot:


Solution

  • Flow highlights this as an error

    That's because it is an error! The first parameter to a template literal function is an Array<string>, not a string. Your code would still execute because ['foo'].toString() === 'foo', but it would easily break in the general case. Therefor you should change

    const A = (actionType: string) => 'COUNTER_' + actionType;
    

    to

    const A = (actionType: Array<string>) => 'COUNTER_' + actionType[0];
    

    Potentially it might also be good to throw an exception if actionType.length > 1.