How can Flow be forced to cast a value to another type?

后端 未结 4 1553
执笔经年
执笔经年 2021-01-01 09:53

Is it possible to forcibly cast a variable in Flow?

type StringOrNumber = string | number
const foo: StringOrNumb         


        
4条回答
  •  萌比男神i
    2021-01-01 10:27

    An update, perhaps, on one or more of the existing answers: There is currently a fairly nice way to specifically tell Flow not to worry about what it thinks is a bad cast.

    You can give an error suppression directive with a specific error code, like this:

    type StringOrNumber = string | number
    const foo: StringOrNumber = 'hello'
    
    // I look for something like `const bar:string = (string) foo`
    // const bar: string = foo // would fail
    // $FlowExpectedError[incompatible-cast]
    const baz: string = (foo: string) // no longer fails!!
    

    As an extra bonus, here is yet another way to perform the cast without any complaint from Flow:

    /*:: if (typeof foo !== "string") throw null; */
    const baz: string = (foo: string) // does not fail!!
    

    Here the special /*:: syntax tells Flow that it should treat the text within the comment (other than the colons) as if it were normal JavaScript code. I gather from the documentation that this feature exists to provide a way to decorate your code with Flow-specific syntax without preventing it from also functioning as pure JavaScript - which has the modest benefit of allowing Flow to be used without any Flow-syntax-stripping tool like Babel or whatever. But the feature also works nicely as a mechanism for expressing "assertions" that only Flow can read. It's a bit hacky, but I personally think it's clean enough to use in a serious project! I mean, as long as you only do it once in a while...

    Of course you could leave the typeof check in actual JavaScript that will actually run, but that could conceivably have a runtime cost I imagine? This, on the other hand, will surely not.

提交回复
热议问题