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

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

Is it possible to forcibly cast a variable in Flow?

type StringOrNumber = string | number
const foo: StringOrNumb         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 10:15

    Flow doesn't do direct casting from one type to another, but you can do something like

    const bar: string = (foo: any);
    

    so you cast foo to an any, because any accepts any type of value as an input. Then because the any type also allows you to read all possible types from it, you can assign the any value to bar because an any is also a string.

提交回复
热议问题