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

czerny picture czerny · Dec 26, 2016 · Viewed 14.3k times · Source

Is it possible to forcibly cast a variable in Flow?

type StringOrNumber = string | number
const foo: StringOrNumber = 'hello'

// I look for something like `const bar:string = (string) foo`
const bar: string = foo // fails
const bar: string = (foo: string) // also fails

Answer

loganfsmyth picture loganfsmyth · Dec 26, 2016

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.