New type casting syntax for Flow: “as”

George Zahariev
Flow
2 min readFeb 6, 2024

--

To make it easier for new users to get started with Flow, we’re updating our type casting syntax to use “as”, like TypeScript, Hack, Swift, and others. Say goodbye to the old colon-and-parens syntax:

// Before:
(1: number);
// After:
1 as number;

It’s safe, unlike TypeScript

Our new type casting syntax behaves just like the old one — no unsafe downcasts allowed, unlike TypeScript’s “as” cast:

const fooObj = {foo: 1};
// The following errors in Flow, but is allowed in TypeScript!
const otherObj = fooObj as {foo: number, bar: string}; // Uh oh
const s: string = otherObj.bar; // Oh dear

As before, and like TypeScript, “as” performs a type-checking cast, not a runtime one.

Adoption

To use the new as casting syntax, you need to update your tooling to support the new syntax:

Update your codebase:

  • Add “casting_syntax=both” to the “[options]” section of your .flowconfig (“both” will become the default value as of Flow version 0.229). This allows you to use both the old colon-cast and the “as” casting syntax.
  • To codemod your code, get flow-upgrade version 2.3.0+, and run “yarn run flow-codemod typeCastToAsExpression”.
  • When you have completed codemodding your codebase, you can update the option to “casting_syntax=as” — this will turn using the old casting syntax into an error, with a quickfix to the “as” casting syntax.
  • At some point in the future we will remove the option and only support “as” casts, so code update your codebase!

--

--