Search code examples
javascriptflowtype

string is incompatible with string literal


I got flow error from this code snippet

type MyType = 'aa' | 'bb'

const str = 'a'
const test1: MyType = `a${str}` // ERROR
const test2: MyType = 'a' + str // ERROR

Error

const test1: MyType = `a${str}` // ERROR
                         ^ Cannot assign template string to `test1` because: Either string [1] is incompatible with string literal `aa` [2]. Or string [1] is incompatible with string literal `bb` [3].
References:
6: const test1: MyType = `a${str}`  // ERROR
                         ^ [1]
3: type MyType = 'aa' | 'bb'
                 ^ [2]
3: type MyType = 'aa' | 'bb'
                        ^ [3]

Link: https://flow.org/try

Does anyone know why flow doesn't support this? Or is there a better way to write this code to make flow happy? Thanks!


Solution

  • Flow is a static type checker for Javascript. Which means that flow only analyses the source code in a static way.

    In your example, test1 and test2 variables would both become equal to aa at runtime, which is equal to one of both authorised values for MyType.

    Unfortunately, this is a runtime result. Flow only checks static rules. As far as I can see, Flow never executes the code it checks (even if the code is trivial like in your example).