<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by George Zahariev on Medium]]></title>
        <description><![CDATA[Stories by George Zahariev on Medium]]></description>
        <link>https://medium.com/@gkz?source=rss-95a4c0399e1f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nFcMwZ15r7EnAmgTdOLXhA.jpeg</url>
            <title>Stories by George Zahariev on Medium</title>
            <link>https://medium.com/@gkz?source=rss-95a4c0399e1f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:31:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gkz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JavaScript Pattern Matching with Flow]]></title>
            <link>https://medium.com/flow-type/javascript-pattern-matching-with-flow-a2a143108897?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2a143108897</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[flowtype]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 17:06:35 GMT</pubDate>
            <atom:updated>2026-06-09T21:27:51.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAdxb8yhpqxa73gnpxi-vQ.png" /></figure><p>Branching in JavaScript can be a pain. switch? Full of footguns. Nested conditional ternary expressions? Unreadable. Initializing a let over a bunch of if/else? Verbose. That weird chain of &amp;&amp; in your JSX? No thanks. And none of these handle complex structures or check if you handled every case.</p><p>If you haven’t looked at <a href="https://flow.org/">Flow</a> recently: its syntax has grown so close to TypeScript that most code is hard to tell apart (here’s a <a href="https://flow.org/en/docs/flow-vs-typescript">side-by-side for TypeScript users</a>). But Flow isn’t just type annotations: it adds first-class language features built for safety.</p><p>match expressions and statements are the newest. They branch on a value: the first pattern that matches maps to a result. match destructures as it matches, and it&#39;s exhaustively checked. If you forget a case of the input, Flow tells you what&#39;s missing and prevents that bug from hitting production.</p><h3>An expression, not just a statement</h3><p>switch is a statement. It can&#39;t produce a value, so the moment you want one you&#39;re back to a let you assign across cases, or a conditional ternary chain. match is both a statement and an expression. As an expression, it gives you the value directly:</p><pre>const description = match (action) {<br>  {type: &#39;add&#39;, const text} =&gt; `Add: ${text}`,<br>  {type: &#39;toggle&#39;, const id} =&gt; `Toggle ${id}`,<br>  {type: &#39;remove&#39;, const id} =&gt; `Remove ${id}`,<br>};</pre><p>Each pattern matches <em>and</em> extracts values at the same time. {type: &#39;add&#39;, const text} checks that type is &#39;add&#39; and binds text in one step, no separate destructuring.</p><h3>Exhaustively checked by default</h3><p>Drop a case and Flow tells you exactly which one is missing:</p><pre>type Action =<br>  | {type: &#39;add&#39;, text: string}<br>  | {type: &#39;toggle&#39;, id: string}<br>  | {type: &#39;remove&#39;, id: string};<br>declare const action: Action;<br><br>const description = match (action) {<br>  {type: &#39;add&#39;, const text} =&gt; `Add: ${text}`,<br>  {type: &#39;toggle&#39;, const id} =&gt; `Toggle ${id}`,<br>  // ERROR: add the missing pattern `{type: &#39;remove&#39;, id: _}`<br>};</pre><p>Add a new variant to Action during a later refactor, and every match that doesn&#39;t handle it lights up. Delete a variant and Flow points at the now-dead patterns to remove.</p><h3>A better switch</h3><p>When you want a statement, match is a switch without the footguns. Cases don&#39;t fall through, so there&#39;s no break to forget. Each case is its own block, so use those lets and consts without worry. And just like the expression form, it&#39;s exhaustively checked.</p><pre>// Before<br>switch (command) {<br>  case &#39;delete&#39;:<br>  case &#39;remove&#39;:<br>    data.pop();<br>    break;<br>  case &#39;add&#39;:<br>    data.push(1);<br>    break;<br>  default:<br>    show(data);<br>}<br>// After<br>match (command) {<br>  &#39;delete&#39; | &#39;remove&#39; =&gt; {<br>    data.pop();<br>  }<br>  &#39;add&#39; =&gt; {<br>    data.push(1);<br>  }<br>  _ =&gt; {<br>    show(data);<br>  }<br>}</pre><p>&#39;delete&#39; | &#39;remove&#39; is an <em>or-pattern</em>: one block for several patterns. _ is the wildcard, matching anything left over.</p><h3>Patterns go deep</h3><p>Patterns aren’t limited to single values. They reach into nested objects and arrays, binding as they go:</p><pre>const name = match (entity) {<br>  {type: &#39;user&#39;, details: {const name}} =&gt; name,<br>  {type: &#39;page&#39;, pageInfo: {const pageName}} =&gt; pageName,<br>  {type: &#39;employee&#39;, const preferredName} =&gt; preferredName,<br>};</pre><p>They match arrays and tuples by shape, so you can branch on several values at once. Exhaustiveness works here too: leave a combination out and Flow tells you the fix.</p><pre>const style = match ([align, position]) {<br>  [&#39;start&#39;, &#39;above&#39;] =&gt; styles.alignTopLeft,<br>  [&#39;start&#39;, &#39;below&#39;] =&gt; styles.alignBottomLeft,<br>  [&#39;end&#39;, &#39;above&#39;] =&gt; styles.alignTopRight,<br>  // ERROR: add the missing pattern `[&#39;end&#39;, &#39;below&#39;]`<br>};</pre><h3>Conditional React rendering, finally readable</h3><p>Conditional rendering in React is exactly what match expressions are for:</p><pre>function Page({tab}: {tab: &#39;home&#39; | &#39;details&#39; | &#39;settings&#39;}) {<br>  return match (tab) {<br>    &#39;home&#39; =&gt; &lt;Home /&gt;,<br>    &#39;details&#39; =&gt; &lt;DetailsPane /&gt;,<br>    &#39;settings&#39; =&gt; &lt;Settings /&gt;,<br>  };<br>}</pre><p>No ternary nest, no stray &amp;&amp;, and if a new tab is added to the union, Flow makes you handle it.</p><h3>Try it</h3><p>match brings exhaustiveness, destructuring, and readable branching together in one construct. It&#39;s the kind of language-level feature Flow exists to add: not just describing the JavaScript you already write, but giving you better JavaScript to write.</p><p>It’s available now.</p><ul><li>Read the <a href="https://flow.org/en/docs/match">docs on </a><a href="https://flow.org/en/docs/match">match</a>, including if guards, as patterns, and more</li><li>Moving off switch? See the <a href="https://flow.org/en/docs/match/migration/">migration guide</a></li><li>Coming from TypeScript? See <a href="https://flow.org/en/docs/flow-vs-typescript">Flow for TypeScript Users</a></li><li>Try it live in the <a href="https://flow.org/try">Flow playground</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2a143108897" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/javascript-pattern-matching-with-flow-a2a143108897">JavaScript Pattern Matching with Flow</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flow for TypeScript Users in 2026]]></title>
            <link>https://medium.com/flow-type/flow-for-typescript-users-in-2026-ad07ac0a2d92?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad07ac0a2d92</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flowtype]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 23:30:49 GMT</pubDate>
            <atom:updated>2026-06-16T19:24:22.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oer_57DM098C7FN19myK1w.png" /></figure><p>In 2026 <a href="https://flow.org/">Flow</a> has changed in three ways that matter:</p><ul><li><strong>Flow’s syntax has converged with TypeScript’s:</strong> if you know TypeScript, you already know most of Flow.</li><li><strong>Flow has features TypeScript lacks:</strong> match expressions and first-class component/hook/renders.</li><li><strong>Where the two diverge, Flow keeps the safer default:</strong> catching patterns TypeScript accepts that can throw at runtime, silently corrupt values, or cause logic bugs.</li></ul><h3>Flow and TypeScript syntax have converged</h3><p>Is it Flow or TypeScript? You can’t tell:</p><pre>type User = {<br>  readonly name: string,<br>  readonly age: number,<br>  readonly metadata: unknown,<br>};<br><br>function get&lt;K extends keyof User&gt;(user: User, key: K): User[K] {<br>  return user[key];<br>}<br><br>declare const user: User;<br>const age: number = get(user, &#39;age&#39;);</pre><p>If you know TypeScript, this all looks familiar. The example above uses keyof, readonly props, unknown, indexed access (T[K]), and extends bounds - and there&#39;s also conditional types, mapped types, type guards, and as const.</p><p>The rest of this post is where Flow goes beyond TypeScript.</p><h3>Flow-only features</h3><p>Flow has features TypeScript lacks:</p><h3>match expressions and statements</h3><p>Flow has match: pattern matching as an expression. It&#39;s exhaustively checked, with structural patterns that destructure as they match. Forget a case, like type: &#39;remove&#39;, and match flags it and tells you what to add.</p><pre>type Action = <br>  | {type: &#39;add&#39;, text: string}<br>  | {type: &#39;toggle&#39;, id: string}<br>  | {type: &#39;remove&#39;, id: string};<br><br>declare const action: Action;<br><br>const description = match (action) { // ERROR: &#39;remove&#39; case missing<br>  {type: &#39;add&#39;, const text} =&gt; `Add: ${text}`,<br>  {type: &#39;toggle&#39;, const id} =&gt; `Toggle ${id}`,<br>};</pre><p>match also has a statement form: a safer switch with no fall-through and all the features of match expressions.</p><h3>React: component, hook, renders</h3><ul><li><strong>component syntax:</strong> React components as a first-class language construct. Direct prop declaration as named parameters, and React-specific correctness the type-checker can enforce.</li><li><strong>renders types: </strong>declare composition contracts for components. Design systems and libraries can specify what slots accept and what components produce, with the type checker enforcing the contracts across wrapper components.</li><li><strong>hook syntax: </strong>declares hooks as a first-class kind, distinct from regular functions. Flow enforces the <a href="https://react.dev/reference/rules">Rules of React</a> in the type checker: catching conditional calls, hook/function conflation, and unsafe mutations of hook return values during render, without a separate ESLint plugin.</li></ul><pre>component Header(text: string, color: string) {<br>  return &lt;div style={{color}}&gt;{text}&lt;/div&gt;;<br>}<br>component MainHeader(text: string) renders Header {<br>  return &lt;Header text={text} color=&quot;red&quot; /&gt;;<br>}<br><br>component Layout(header: renders Header) {<br>  return &lt;div&gt;<br>    {header}<br>    &lt;section&gt;Content&lt;/section&gt;<br>  &lt;/div&gt;;<br>}<br><br>const ok = &lt;Layout header={&lt;MainHeader text=&quot;Flow&quot; /&gt;} /&gt;;<br>const bad = &lt;Layout header={&lt;footer /&gt;} /&gt;; // ERROR</pre><h3>Four runtime crashes TypeScript doesn’t catch — but Flow does</h3><p>This is where the two still part ways. Each example below type-checks in TypeScript 6.0.3 with strict enabled - then crashes at runtime.</p><ol><li><strong>Extracting a method from an instance loses its </strong><strong>this binding in TypeScript</strong></li></ol><pre>class Counter {<br>  count: number = 0;<br>  increment(): number {<br>    return ++this.count;<br>  }<br>}<br>const counter = new Counter();<br>const tick = counter.increment;  // TS accepts. Flow rejects.<br>tick();  // Runtime crash! `this` is undefined inside `increment`</pre><p>Pulling counter.increment off the instance detaches the method from counter, so the later tick() runs with this undefined and ++this.count throws. TypeScript types the extracted method as a plain function and waves the call through. Flow rejects the unbound method extraction at the point where this is lost.</p><p><strong>2. TypeScript lets extra properties slip through indirect assignment</strong></p><pre>type Prices = {apple: number, banana: number};<br>const items = {apple: 1.5, banana: 0.5, sample: &quot;free&quot;};<br>const prices: Prices = items;  // TS accepts. Flow rejects.<br>Object.values(prices).map(<br>  price =&gt; price.toFixed(2), // Runtime crash! `sample` isn&#39;t a number<br>);</pre><p>TypeScript’ object types allow extra properties at the type level — the “excess property check” that could catch {apple: 1.5, sample: &quot;free&quot;} only fires on <em>direct</em> object literal assignment. Indirect paths (like assigning through a variable) lose that check, and the extra sample property slips through. Flow&#39;s object types are exact by default: extra properties are always rejected.</p><p><strong>3. TypeScript lets you push a wider value into a narrower mutable array</strong></p><pre>// TypeScript: accepted.<br>function appendError(errs: Array&lt;string | Error&gt;) {<br>  errs.push(new Error(&quot;oops&quot;));<br>}<br>const errors: Array&lt;string&gt; = [];<br>appendError(errors);  // TS accepts. Flow rejects.<br>errors[0].toUpperCase();  // Runtime crash! `errors[0]` isn&#39;t a string</pre><p>TypeScript treats Array&lt;string&gt; as a subtype of Array&lt;string | Error&gt; (mutable arrays are covariant in TS), so the call goes through and the push inside appendError adds an Error in the caller&#39;s string-typed array. Flow&#39;s mutable-array invariance blocks the widening at the call site. If the function doesn&#39;t actually need to mutate, the fix is ReadonlyArray&lt;string | Error&gt;: removing the possibility of mutation makes the widening safe.</p><p><strong>4. Type-guard bodies aren’t validated in TypeScript</strong></p><pre>// TypeScript: accepted, but this body is true for numbers, not strings.<br>function isString(x: unknown): x is string {<br>  return typeof x === &quot;number&quot;;  // TS accepts. Flow rejects.<br>}<br>const data: unknown = 1;<br>if (isString(data)) {<br>  data.toUpperCase();  // Runtime crash! `data` isn&#39;t a string<br>}</pre><p>TypeScript checks the <em>signature</em> of a predicate, not the body. Flow validates the body in both directions: every return must actually refine to the guard type, and the negation must refine the guard type away. It rejects predicates that lie about what they check.</p><h3>Read the full comparison</h3><p>The full doc, <a href="https://flow.org/en/docs/flow-vs-typescript/"><strong>Flow for TypeScript Users in 2026</strong></a>, has 20+ side-by-side Flow vs. TypeScript comparisons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad07ac0a2d92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/flow-for-typescript-users-in-2026-ad07ac0a2d92">Flow for TypeScript Users in 2026</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New type casting syntax for Flow: “as”]]></title>
            <link>https://medium.com/flow-type/new-type-casting-syntax-for-flow-as-3ef41567ff3e?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ef41567ff3e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flowtype]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 19:35:06 GMT</pubDate>
            <atom:updated>2024-02-27T23:31:07.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*Qz7Vz1kppEptexmWxwn8ww.png" /></figure><p>To make it easier for new users to get started with <a href="https://flow.org/en/docs/">Flow</a>, 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:</p><pre>// Before:<br>(1: number);<br>// After:<br>1 as number;</pre><h3>It’s safe, unlike TypeScript</h3><p>Our new type casting syntax behaves just like the old one — no unsafe downcasts allowed, unlike TypeScript’s “as” cast:</p><pre>const fooObj = {foo: 1};<br>// The following errors in Flow, but is allowed in TypeScript!<br>const otherObj = fooObj as {foo: number, bar: string};  // Uh oh<br>const s: string = otherObj.bar; // Oh dear</pre><p>As before, and like TypeScript, “as” performs a type-checking cast, not a runtime one.</p><h3>Adoption</h3><p>To use the new as casting syntax, you need to update your tooling to support the new syntax:</p><ul><li>Flow and Flow Parser: 0.220+</li><li>Prettier: 3.1+</li><li>Babel: use the <a href="https://www.npmjs.com/package/babel-plugin-syntax-hermes-parser">babel-plugin-syntax-hermes-parser</a> plugin version 0.19+, see our <a href="https://flow.org/en/docs/tools/babel/">Babel guide</a> for more details.</li><li>ESLint: use <a href="https://www.npmjs.com/package/hermes-eslint">hermes-eslint</a> plugin version 0.19+, see our <a href="https://flow.org/en/docs/tools/eslint/">ESLint guide</a> for more details.</li></ul><p>Update your codebase:</p><ul><li>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.</li><li>To codemod your code, get <a href="https://www.npmjs.com/package/flow-upgrade">flow-upgrade</a> version 2.3.0+, and run “yarn run flow-codemod typeCastToAsExpression”.</li><li>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.</li><li>At some point in the future we will remove the option and only support “as” casts, so code update your codebase!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ef41567ff3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/new-type-casting-syntax-for-flow-as-3ef41567ff3e">New type casting syntax for Flow: “as”</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improved Flow Docs and Try Flow]]></title>
            <link>https://medium.com/flow-type/improved-flow-docs-and-try-flow-5da5e4831b5e?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5da5e4831b5e</guid>
            <category><![CDATA[flowtype]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 18:46:46 GMT</pubDate>
            <atom:updated>2023-09-19T18:54:52.801Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve refreshed our <a href="https://flow.org/en/docs/">documentation</a>, and added the ability to configure options and lints in <a href="https://flow.org/try/">Try Flow</a>!</p><h4>Documentation</h4><p>Over the past 6 months, we’ve reviewed and updated almost every page of our <a href="https://flow.org/en/docs/">documentation</a>, and added new docs for features previously missing. If you’ve looked at our docs in the past and found them outdated, now is the time to take another look!</p><p>Some page highlights:</p><ul><li>The <a href="https://flow.org/en/docs/lang/refinements/">page on refinements</a> has been completely redone to explain the different ways you can refine.</li><li>We’ve added a page visualizing our <a href="https://flow.org/en/docs/lang/type-hierarchy/">type hierarchy</a>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-FY6CARAa-bToGpo" /></figure><p>After we <a href="https://medium.com/flow-type/exact-object-types-by-default-by-default-cc559af6f69">enabled exact object types by default</a>, Try Flow and all documentation examples have been updated to use exact object types by default.</p><p>Finally, our website is now built with <a href="https://docusaurus.io/">Docusaurus</a> — this should make loading and navigation snappy.</p><h4>Try Flow</h4><p><a href="https://flow.org/try/">Try Flow</a> now allows you to enable and disable options and Flow lints! This configuration is saved in the link you share (along with the Flow version you’ve selected). Select the “Config” tab on <a href="https://flow.org/try/">flow.org/try</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TsOrRUxp2_lcD6wd" /></figure><p>We’ll warn you if you open a link specifying an older version of Flow.</p><p>$FlowFixMe suppression comments and types now work in Try Flow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5da5e4831b5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/improved-flow-docs-and-try-flow-5da5e4831b5e">Improved Flow Docs and Try Flow</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing 5 new Flow tuple type features]]></title>
            <link>https://medium.com/flow-type/announcing-5-new-flow-tuple-type-features-ff4d7f11c50a?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff4d7f11c50a</guid>
            <category><![CDATA[flowtype]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 19:56:22 GMT</pubDate>
            <atom:updated>2023-08-17T19:56:22.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Tuples are a lighter weight alternative to objects when you want to group data, by using positions rather than property names to distinguish elements. However, tuple types have lacked many useful features object types provide - until now!</p><ol><li>Labeled tuple elements: type T = [foo: number, bar: string]</li><li>Variance (read-only/write-only) annotations for tuple elements: type T = [+foo: number, -bar: string]</li><li>Optional tuple elements: type T = [foo?: number, bar?: string]</li><li>Tuple spread type T = [number, string, ...OtherTuple]</li><li>Refinement on tuple length</li></ol><p>Read the full <a href="https://flow.org/en/docs/types/tuples/">docs</a>.</p><h3>Labeled tuple elements</h3><p>You can now add a label to tuple elements. Labels do not affect the type of the tuple element, but are useful in self-documenting the purpose of the tuple elements, especially when multiple elements have the same type.</p><pre>type Range = [x: number, y: number];</pre><p>Labels are also necessary to add variance annotations or optionality modifiers to elements.</p><h3>Variance annotations on tuple elements and read-only tuples</h3><p>You can add <a href="https://flow.org/en/docs/lang/variance/">variance</a> annotations (to denote read-only/write-only) on labeled tuple elements, just like on object properties:</p><pre>type T = [+foo: number, -bar: string];</pre><p>This allows you to mark elements as read-only or write-only. For example:</p><pre>function f(readOnlyTuple: [+foo: number, +bar: string]) {<br>  const n: number = readOnlyTuple[0]; // OK to read<br>  readOnlyTuple[1] = 1; // ERROR! Cannot write<br>}</pre><p>You can also use the $ReadOnly on tuple types as a shorthand for marking each property as read-only:</p><pre>type T = $ReadOnly&lt;[number, string]&gt;; // Same as `[+a: number, +b: string]`</pre><h3>Optional tuple elements</h3><p>You can mark tuple elements as optional with ? after an element’s label. This allows you to omit the optional elements. Optional elements must be at the end of the tuple type, after all required elements.</p><pre>type T = [foo: number, bar?: string];<br>([1, &quot;s&quot;]: T); // OK: has all elements<br>([1]: T); // OK: skipping optional element</pre><p>You cannot write undefined to the optional element - add | void to the element type if you want to do so:</p><pre>type T = [foo?: number, bar?: number | void];<br>declare const x: T;<br>x[0] = undefined; // ERROR<br>([undefined]: T); // ERROR<br><br>x[1] = undefined; // OK: we&#39;ve added `| void` to the element type</pre><p>You can also use the Partial and Required utility types to make all elements optional or required respectively:</p><pre>type AllRequired = [number, string];<br>([]: Partial&lt;AllRequired&gt;); // OK: like `[a?: number, b?: string]` now<br><br>type AllOptional = [a?: number, b?: string];<br>([]: Required&lt;AllOptional&gt;); // ERROR: like `[a: number, b: string]` now</pre><p>Tuples with optional elements have an arity (length) that is a range rather than a single number. For example, [number, b?: string] has an length of 1-2.</p><h3>Tuple type spread</h3><p>You can spread a tuple type into another tuple type to make a longer tuple type:</p><pre>type A = [number, string];<br>type T = [...A, boolean]; // Same as `[number, string, boolean]`<br>([1, &quot;s&quot;, true]: T); // OK</pre><p>Tuple spreads preserve variance and optionality. You cannot spread arrays into tuples, only other tuples.</p><h3>Refinement on length</h3><p>You can refine a union of tuples by their length:</p><pre>type Union = [number, string] | [boolean];<br>function f(x: Union) {<br>  if (x.length === 2) {<br>    // `x` is `[number, string]`<br>    const n: number = x[0]; // OK<br>    const s: string = x[1]; // OK<br>  } else {<br>    // `x` is `[boolean]`<br>    const b: boolean = x[0];<br>  }<br>}</pre><p>Technically this is not a newly added feature, but one not previously announced.</p><h3>Adoption</h3><p>To use labeled tuple elements (including optional elements and variance annotations on elements) and tuple spread elements, you need to upgrade your infrastructure so that it supports the syntax:</p><ul><li>flow and flow-parser: 0.212.0</li><li>prettier: 3</li><li>babel with babel-plugin-syntax-hermes-parser. See <a href="https://flow.org/en/docs/tools/babel/">our Babel guide</a> for setup instructions.</li><li>eslint with hermes-eslint. See <a href="https://flow.org/en/docs/tools/eslint/">our ESLint guide</a> for setup instructions.</li></ul><h3>Bonus: declare const &amp; declare let</h3><p>Flow now supports declare const and declare let (in addition to the existing declare var). These allow you to declare a variable with a type, but without an implementation. They are useful for writing library definitions or creating reproductions of issues in Try Flow, while using the modern const and let instead of the legacy var. Both declare const and declare let are block-scoped, like their non-declare equivalents.</p><pre>if (cond) {<br>  declare const foo: number;<br>}<br>foo; // ERROR: cannot resolve `foo` (as it&#39;s block-scoped)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff4d7f11c50a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/announcing-5-new-flow-tuple-type-features-ff4d7f11c50a">Announcing 5 new Flow tuple type features</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing Partial & Required Flow utility types + catch annotations]]></title>
            <link>https://medium.com/flow-type/announcing-partial-required-flow-utility-types-catch-annotations-3a32f0bf2a20?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a32f0bf2a20</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flowtype]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 20:02:56 GMT</pubDate>
            <atom:updated>2023-03-15T20:02:56.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAWZHLO6O7pSAxP079bUcg.png" /></figure><p>Starting in Flow version 0.201, make an object type’s fields all optional using Partial&lt;ObjType&gt; (use instead of the unsafe $Shape), and make an object type’s optional fields required with Required&lt;ObjType&gt;. Also, you can now annotate a catch variable with mixed.</p><h3>Partial&lt;T&gt;</h3><p>The <a href="https://flow.org/en/docs/types/utilities/#toc-partial">Partial</a> utility type converts all of an object or interface’s fields to be optional. For example:</p><pre>type Person = {<br>  name: string,<br>  age: number,<br>};<br>type PartialPerson = Partial&lt;Person&gt;;<br>// Above equivalent to `{name?: string, age?: number}`<br><br>const a: PartialPerson = {}; // OK<br>const b: PartialPerson = {name: &#39;George&#39;}; // OK<br>const c: PartialPerson = {name: &#39;George&#39;, age: 123}; // OK</pre><p>This utility replaces the unsafe $Shape utility: use Partial now instead.</p><p>Note: while this is the first time we have announced the Partial utility type, it has existed for a while, and had the name $Partial. You should codemod any existing $Partial usages to Partial. We will remove support for the old alias $Partial from version 0.203.</p><h3>No longer in love with the $Shape of U</h3><p>Why use Partial instead of $Shape? $Shape allows you to unsafely use $Shape&lt;U&gt; as U in some contexts, for example:</p><pre>type PersonShape = $Shape&lt;Person&gt;;<br>const personShape: PersonShape = {name: &#39;George&#39;};<br>const person: Person = personShape; // Unsafe - doesn&#39;t have `age` prop<br>const age: number = person.age; // Unsafe - actually `undefined`</pre><p>It is also not equivalent to itself in some contexts:</p><pre>function f&lt;U&gt;(input: $Shape&lt;U&gt;): $Shape&lt;U&gt; {<br>    return input; // ERROR: `U` is incompatible with `$Shape` of `U`<br>}</pre><p>Partial does not have any of these problems - use it instead!</p><p>We will remove support for $Shape from version 0.203 or later.</p><h3>Required&lt;T&gt;</h3><p>The <a href="https://flow.org/en/docs/types/utilities/#toc-required">Required</a> utility type is the opposite of Partial: it converts all of an object or interface’s optional fields to be required. For example:</p><pre>type PartialPerson = {<br>  name?: string,<br>  age?: number,<br>};<br>type Person = Required&lt;PartialPerson&gt;;<br>// Above equivalent to `{name: string, age: number}`<br><br>const a: Person = {name: &#39;George&#39;, age: 123}; // OK<br>const b: Person = {age: 123}; // ERROR: missing `name` property</pre><h3>Migrate your $Shape and $Partial usage</h3><p>We will remove support for $Shape from version 0.203 or later. You should codemod any instances of it to Partial. This may cause new errors, due to the safety issues of $Shape described above. In some contexts $ReadOnly&lt;Partial&lt;T&gt;&gt; may be a better replacement for $Shape&lt;T&gt;, you can try and see if that causes less errors than just Partial&lt;T&gt;.</p><p>You can either use flow-upgrade or just regular expressions to codemod your codebase.</p><p>Flow upgrade:<br>Get at least version 2.2.0 of <a href="https://www.npmjs.com/package/flow-upgrade">flow-upgrade</a> and run</p><ul><li>$Shape to Partial: yarn run flow-codemod convertShapeToPartial</li><li>$Partial to Partial: yarn run flow-codemod renamePartial</li></ul><p>Regular expressions:</p><ul><li>$Shape to Partial: sed -i &#39;s/\$Shape&lt;/Partial&lt;/g&#39;</li><li>$Partial to Partial: sed -i &#39;s/\$Partial&lt;/Partial&lt;/g&#39;</li></ul><h3>Bonus feature: Catch variable annotations</h3><p>You can now annotate catch variables as exactly either any or mixed. Without an annotation they continue to be typed as any as before. By using mixed, you can improve your safety and Flow coverage, at the trade-off of increased runtime checks:</p><pre>try {<br>  danger();<br>} catch (e: mixed) {<br>  if (e instanceof MyError) {<br>    handleMyError(e);<br>  } else if (e instanceof Error) {<br>    handleError(e);<br>  } else {<br>    throw e;<br>  }<br>}</pre><p>You can choose to make mixed the default type of catch variables by enabling the option use_mixed_in_catch_variables=true in your .flowconfig <a href="https://flow.org/en/docs/config/options/#toc-use-mixed-in-catch-variables">[docs]</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a32f0bf2a20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/announcing-partial-required-flow-utility-types-catch-annotations-3a32f0bf2a20">Announcing Partial &amp; Required Flow utility types + catch annotations</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exact object types by default, by default]]></title>
            <link>https://medium.com/flow-type/exact-object-types-by-default-by-default-cc559af6f69?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc559af6f69</guid>
            <category><![CDATA[flowtype]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 18:07:09 GMT</pubDate>
            <atom:updated>2023-02-16T18:13:11.614Z</atom:updated>
            <content:encoded><![CDATA[<p>We <a href="https://medium.com/flow-type/on-the-roadmap-exact-objects-by-default-16b72933c5cf">announced 5 years ago</a> a plan to eventually make <a href="https://flow.org/en/docs/types/objects/#toc-exact-object-types">exact object types</a> the <a href="https://flow.org/en/docs/config/options/#toc-exact-by-default-boolean">default</a>. We are now proceeding with this plan. Starting with Flow 0.200, you must explicitly set either exact_by_default=true or exact_by_default=false in the [options] section of your .flowconfig, as we have eliminated the default value (which was false). From Flow 0.202, a default value will be added again, this time as exact_by_default=true.</p><p>In future versions, we will take steps to make exact_by_default=true the default value if no option is set, and then eventually delete the option completely. Take a look at the “Call to action” section at the end of this post to learn how to update your codebase.</p><h3>Exact object types</h3><p><a href="https://flow.org/en/docs/types/objects/#toc-exact-object-types">Exact object types</a> permit only the properties listed - no extra properties are allowed. Inexact object types permit additional, unknown properties.</p><p>When exact_by_default=false (previously the default):</p><pre>type ExplicitlyExact = {|a: number, b: string|};<br>type ExplicitlyInexact = {a: number, b: string, ...};<br>type ImplicitlyInexact = {a: number, b: string}; // Inexact</pre><p>With exact_by_default=true (the future default):</p><pre>type ExplicitlyExact = {|a: number, b: string|};<br>type ExplicitlyInexact = {a: number, b: string, ...};<br>type ImplicitlyExact = {a: number, b: string}; // Exact</pre><h3>Plan</h3><ol><li>Require that exact_by_default is set in the .flowconfig, either to true or false, and error if the option is missing. From Flow 0.200</li><li>Remove the above error and make the default, if the option is not specified, exact_by_default=true. From Flow 0.202</li><li>Enable the <a href="https://flow.org/en/docs/linting/rule-reference/#toc-implicit-inexact-object">implicit-inexact-object</a> lint by default as an error (only in effect when exact_by_default=false). This requires either {|foo: T|} or {foo: T, ...}. Later this year.</li><li>Delete the option and associated lints, no longer allow exact_by_default=false. Later this year.</li></ol><h3>Call to action</h3><p>If you already have set exact_by_default=true in your .flowconfig, you don’t need to take any action at the moment. In the future, when the option is deleted, all you will need to do is delete that line from your .flowconfig.</p><p>If you have not set the above option at all, then to preserve the previous default behavior you can add exact_by_default=false to your .flowconfig.</p><p>We plan on completely removing the option in the future. To update your codebase so you can enable exact_by_default=true, read through <a href="https://medium.com/flow-type/how-to-upgrade-to-exact-by-default-object-type-syntax-7aa44b4d08ab">this blog post from 2020</a>. In short:</p><ul><li>Install flow-upgrade (it expects prettier as a peer dependency) <a href="https://www.npmjs.com/package/flow-upgrade">[npm]</a></li><li>Run yarn run flow-codemod convertImplicitInexactObjectTypes (or npm equivalent). This will convert all implicit inexact object types, e.g. {a: number, b: string}, to be explicit, e.g. {a: number, b: string, ...}</li><li>Enable implicit-inexact-object=error in the [lints] section in your .flowconfig <a href="https://flow.org/en/docs/linting/rule-reference/#toc-implicit-inexact-object">[docs]</a></li><li>Fix any remaining errors that arise, until you have no errors due to the above lint</li><li>Change exact_by_default to true in your .flowconfig, and turn off the implicit-inexact-object lint</li><li>Codemod all explicitly exact object types, e.g. {|a: number|}, to remove the | (now that they are the default). Run yarn run flow-codemod removeExplicitlyExactObjectTypeSyntax (or npm equivalent) to turn that example into {a: number}</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc559af6f69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/exact-object-types-by-default-by-default-cc559af6f69">Exact object types by default, by default</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improved handling of the empty object in Flow]]></title>
            <link>https://medium.com/flow-type/improved-handling-of-the-empty-object-in-flow-ead91887e40c?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ead91887e40c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flowtype]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Thu, 20 Oct 2022 18:20:38 GMT</pubDate>
            <atom:updated>2023-01-07T01:25:17.485Z</atom:updated>
            <content:encoded><![CDATA[<p>Flow handled the empty object literal {} in a permissive but unsafe way. The fix increases safety and predictability, but requires using different patterns and behavior described in this post.</p><p>Flow treated the empty object literal {}as an object which could change over time as values were written to and read from it (we called this “<a href="https://flow.org/en/docs/types/objects/#toc-unsealed-objects">unsealed</a>”). This was purposely done when Flow first started to be adopted, in order to support the existing pattern of multi-line object initialization. However, this also lead to a lot of unsafe behavior and user frustration.</p><p>We have fixed these issues, but now require some new patterns to be used. This change not only improves safety, but also unblocks Flow’s move to <a href="https://medium.com/flow-type/introducing-local-type-inference-for-flow-6af65b7830aa">local type inference</a>.</p><h4>The Problems</h4><p>1) You could read non-existent properties from the object, and this access would result in any:</p><p>const obj = {};<br>const n: number = obj.XXX; // Previously allowed, now an error</p><p>2) You could use an empty object where an object with properties was expected:</p><p>const obj: {prop: boolean, ...} = {}; // Previously allowed, now an error</p><p>3) The empty object was considered “<a href="https://flow.org/en/docs/types/objects/#toc-exact-object-types">inexact</a>”, so was not a valid value for an exact object with optional properties:</p><p>declare function f({|prop?: boolean|}): void; f({}); // An error previously, now ok<br>const obj: {||} = {}; // Also an error previously, now ok</p><p>4) Spreads involving the empty object were also unsafe:</p><p>const obj = {}; <br>function f() { obj.foo = 3; } // Function never called <br>let y: {foo: number} = {...obj}; // Previously allowed</p><h4>The Solutions</h4><p>Now the empty object literal is treated as an empty exact object (with no properties), resolving the above issues.</p><p>const obj: {||} = {}; // Now ok!<br>obj.XXX; // Error: property &#39;XXX&#39; doesn&#39;t exist on &#39;obj&#39;</p><p>To support this, we made changes to both Flow itself and have some new suggested patterns to use in your code.</p><p>To enable:</p><ul><li>For Flow versions 0.184–0.190, the behavior is off by default, but can be enabled by adding exact_empty_objects=true to your .flowconfig</li><li>The option is enabled by default in Flow version 0.191</li><li>The .flowconfig flag was deleted in Flow version 0.192, and behavior is enabled permanently</li></ul><p>We have created various codemods to assist you in your migration. You must be using Flow version 0.184–0.191 to run the codemods, as they may be deleted when the flag was deleted (0.192). They are mentioned under the subheadings below. Note that given the previous unsafe behavior of the empty object, even after running codemods it is normal to have many Flow errors which will require $FlowFixMe comments to suppress — more legitimately unsafe behavior is now being caught.</p><h4>Object Access</h4><p>We changed how we treat object access in Flow. Consider the following pattern:</p><p>const maybeObj: ?{a: number} = ...;<br>const obj = maybeObj ?? {};<br>obj.a;</p><p>Previously, this only worked because we unsafely allowed arbitrary reads from the unsealed empty object. If we treated the empty object as exact, then we would get an error cannot read property &#39;a&#39; from &#39;{}&#39;.</p><p>We modified how object access is handled: now if you access a property on a union (from the above {a: number} | {}), and the access succeeds in one case (e.g. from the {a: number}), rather than erroring for the other cases (e.g. {}), if the other cases are exact allow it and add void to the resulting type (in our example, obj.a would have the type number | void). This mirrors what happens at runtime, and matches users expectations.</p><p>If one of the members of the union is inexact, and does not have the property, we still error as an inexact object could have that property with some arbitrary type (so we cannot just add void).</p><p>This behavior has been enabled since version 0.174.</p><h4>Object initialization</h4><p>Instead of initializing an object over multiple lines, either create it all at once in one literal or use an annotation. Consider</p><p>const obj = {};<br>obj.a = 1;<br>obj.b = 2;</p><p>This will now cause errors as obj is not typed as having properties a and b. Instead you should create the object literal all at once:</p><p>const obj = {a: 1, b: 2};</p><p>A similar case to the above, say you have</p><p>const obj = {};<br>if (cond) { obj.a = 1; }</p><p>You cannot collapse this into an object literal. However, you can add an annotation to obj with optional properties:</p><p>const obj: {a?: number} = {};<br>if (cond) { obj.a = 1; }</p><p>Codemod: Get the latest <a href="https://www.npmjs.com/package/flow-upgrade">flow-upgrade</a> package and then runyarn run flow-codemod collapseObjectInitialization</p><h4>Dictionaries</h4><p>Objects used as dictionaries require annotations. Consider</p><p>const dict = {};<br>for (const x of arr) { dict[x] = f(x); }</p><p>We are treating the object like a dictionary, with the empty object being the empty dictionary. You need to add an annotation to type it as a dictionary:</p><p>const dict: {[string]: number} = {};<br>for (const x of arr) { dict[x] = f(x); }</p><p>Using object dictionaries with .reduce is a common pattern - you can supply the type argument to .reduceto give the type of the empty object initializer:</p><p>arr.reduce&lt;{[string]: number}&gt;((acc, x) =&gt; acc[x] = f(x), {});</p><p>Codemod: flow codemod annotate-empty-object --write</p><h4>Object.assign</h4><p>Instead of using Object.assign on an empty object, use object spread instead. Consider</p><p>const obj = Object.assign({}, a, b);</p><p>Flow requires the “target” of Object.assign (the first parameter), to have the properties that that latter arguments will assign to. If the first argument of Object.assign is an object literal (as in the case of {}), you can transform it to an object spread instead:</p><p>const obj = {...a, ...b};</p><p>Use object spread instead of Object.assign for the above pattern.</p><p>Codemod: Enable the existing ESLint rule <a href="https://eslint.org/docs/latest/rules/prefer-object-spread">prefer-object-spread</a> as an error and run its autofixer on your codebase, e.g. eslint --rule &#39;{&quot;prefer-object-spread&quot;:2}&#39; --fix</p><h4>useState</h4><p>Supply a type parameter if calling useState with an empty object initial value. Consider</p><p>const [foo, setFoo] = useState({});</p><p>You can’t access any properties from foo, as it doesn’t have any. You can solve this by supplying the explicit type argument:</p><p>const [foo, setFoo] = useState&lt;{a?: number}&gt;({});</p><p>Codemod: flow codemod annotate-use-state --write</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ead91887e40c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/improved-handling-of-the-empty-object-in-flow-ead91887e40c">Improved handling of the empty object in Flow</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Enums vs. Flow Enums]]></title>
            <link>https://medium.com/flow-type/typescript-enums-vs-flow-enums-83da2ca4a9b4?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/83da2ca4a9b4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[flowtype]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 17:41:21 GMT</pubDate>
            <atom:updated>2021-09-13T17:42:29.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSqim48oqxcC_OTw1vnObg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@davidohboy?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">David Selbert</a> from <a href="https://www.pexels.com/photo/fluffy-deer-on-snowy-meadow-near-forest-6468213/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>The Flow team recently <a href="https://medium.com/flow-type/introducing-flow-enums-16d4239b3180">announced Flow Enums</a>, a new language feature from Flow. If you’re familiar with TypeScript, you might be wondering how this feature compares to <a href="https://www.typescriptlang.org/docs/handbook/enums.html">TypeScript’s enums</a>. While they superficially look similar, they are quite different.</p><p>This is an overview of some of the differences between TypeScript and Flow Enums. For full details read the <a href="https://flow.org/en/docs/enums/">Flow Enums documentation</a>.</p><h3>Exhaustive checking in switch statements</h3><p>Flow Enums are always <a href="https://flow.org/en/docs/enums/using-enums/#toc-exhaustively-checking-enums-with-a-switch">exhaustively checked in </a><a href="https://flow.org/en/docs/enums/using-enums/#toc-exhaustively-checking-enums-with-a-switch">switch statements</a>. If you forget a member, Flow will error:</p><pre>// Flow:<br>enum Status {<br>  Active = 0,<br>  Paused = 1,<br>  Off = 2,<br>}</pre><pre>const x: Status = ...;</pre><pre>// ERROR: Incomplete exhaustive check: the member `Off` of enum <br>// `Status` has not been considered in check of `status`<br>switch (x) {<br>  case Status.Active: break;<br>  case Status.Paused: break;<br>  // We forgot to add `case: Status.Off:` here,<br>  // resulting in error above<br>}</pre><p>TypeScript enums are not always exhaustively checked in switch statements: TypeScript will not complain if you miss a case like in the above example.</p><h3>Implicit coercion</h3><p>Flow Enums do not allow for implicit coercion to the enum type. Instead, you can make an explicit type-safe cast using the <a href="https://flow.org/en/docs/enums/using-enums/#toc-cast">.cast enum method</a>, which returns undefined if the value is not valid:</p><pre>// Flow:<br>enum Status {<br>  Active = 0,<br>  Paused = 1,<br>  Off = 2,<br>}</pre><pre>const num: number = 1;<br>// ERROR: `number` is incompatible with `Status`:<br>const incorrect: Status = num;</pre><pre>// Safe casts using the `.cast` method:<br>const maybeStatus: Status | void = Status.cast(num);<br>// Can use ?? for default:<br>const status: Status = Status.cast(num) ?? Status.Off;</pre><p>TypeScript enums can allow for implicit coercions, including unsafe ones:</p><pre>// TypeScript:<br>enum Status {<br>  Active = 0,<br>  Paused = 1,<br>  Off = 2,<br>}</pre><pre>const num: number = 1;<br>const x: Status = num; // Allowed in TypeScript<br>const y: Status = 42; // Allowed in TypeScript</pre><p>Flow Enums also do not allow implicit coercions the other way, from enum type to representation type, to prevent logic bugs. You can still explicitly do so with a type cast:</p><pre>// Flow:<br>enum Currency {<br>  USD = 0,<br>  CAD = 1,<br>  GBP = 2,<br>}<br>declare function getExchangeRate(currency: Currency): number;</pre><pre>// Forgot to call `getExchangeRate` on `Currency.CAD`<br>// ERROR: `Currency` is not a `number`:<br>const balanceUSD = 100 * Currency.CAD;</pre><pre>// You can explicitly cast to number if you wish:<br>const x: number = (Currency.CAD: number);</pre><p>TypeScript enums implicitly coerce to their underlying type:</p><pre>// TypeScript:<br>enum Currency {<br>  USD = 0,<br>  CAD = 1,<br>  GBP = 2,<br>}</pre><pre>// Forgot to call `getExchangeRate`:<br>const balanceUSD = 1000 * Currency.CAD; // Allowed in TypeScript<br>const x: number = Currency.CAD; // Allowed in TypeScript</pre><h3>Default member values</h3><p>Flow Enums do not default number values. They require explicit number values specified for a <a href="https://flow.org/en/docs/enums/defining-enums/#toc-number-enums">number enum</a>.</p><pre>// Flow:<br>enum Status {<br>  Active = 0, // Explicit number value required<br>  Paused = 1,<br>  Off = 2,<br>}</pre><p>TypeScript enums default number values, when they are not supplied:</p><pre>// TypeScript:<br>enum Status {<br>  Active, // Has value 0<br>  Paused, // Has value 1<br>  Off, // Has value 2<br>}</pre><p>Flow does not allow defaulting of number enums because if a member from the middle of such an enum is added or removed, all subsequent member values would be implicitly changed. This can be unsafe (e.g. serialization, logging, push safety). Requiring the user to be explicit about the renumbering makes them think about the consequences of doing so.</p><p>Since we do not default number values, a Flow Enum without values specified defaults to <a href="https://flow.org/en/docs/enums/defining-enums/#toc-string-enums">string values</a> which mirror the member names. Since each member name is unique and does not depend on the order of the members, it does not have the same issues as described above.</p><pre>// Flow:<br>enum Status {<br>  Active, // Has value &quot;Active&quot;<br>  Paused, // Has value &quot;Paused&quot;<br>  Off, // Has value &quot;Off&quot;<br>}</pre><p>Mirrored string enums also allow for more optimized runtime implementations of the .cast, .isValid, and .getName <a href="https://flow.org/en/docs/enums/using-enums/#toc-methods">methods</a>, since the name is equivalent to the value.</p><h3>Extending the enum</h3><p>Flow Enums <a href="https://flow.org/en/docs/enums/defining-enums/#toc-fixed-at-declaration">cannot be extended or modified</a>. Once they are defined, they act like frozen objects.</p><p>TypeScript can allow enums to be modified or extended. This can interact with TypeScript’s implicit default number values discussed above:</p><pre>// TypeScript:<br>enum Status {<br>  Active = 0,<br>  Paused = 1,<br>  Off = 2<br>}<br>enum Status {<br>  // Due to TypeScript&#39;s default values, this is implicitly `0`:<br>  Disabled,<br>}</pre><pre>console.log(Status.Disabled === Status.Active); //=&gt; true</pre><h3>Reverse mapping</h3><p>For any kind of Flow Enum, if you have an enum value and want to get the name of the member for that value (e.g. for debugging, CRUD UIs), you can use the <a href="https://flow.org/en/docs/enums/using-enums/#toc-getname">.getName method</a>:</p><pre>// Flow:<br>enum Status {<br>  Active = 0,<br>  Paused = 1,<br>  Off = 2,<br>}</pre><pre>console.log(Status.getName(Status.Off)); //=&gt; &quot;Off&quot;</pre><pre>enum StatusStr {<br>  Active = &quot;a&quot;,<br>  Paused = &quot;p&quot;,<br>  Off = &quot;o&quot;,<br>}</pre><pre>console.log(StatusStr.getName(StatusStr.Off)); //=&gt; &quot;Off&quot;</pre><p>TypeScript directly adds a reverse mapping to the enum object, but only for number enums (not for string enums):</p><pre>// TypeScript:<br>enum Status {<br>  Active = 0,<br>  Paused = 1,<br>  Off = 2,<br>}</pre><pre>console.log(Status[Status.Off]); //=&gt; &quot;Off&quot;</pre><pre>enum StatusStr {<br>  Active = &quot;a&quot;,<br>  Paused = &quot;p&quot;,<br>  Off = &quot;o&quot;,<br>}</pre><pre>// ERROR: TypeScript doesn&#39;t support this for string enums:<br>StatusStr[StatusStr.Off];</pre><h3>Iterating over enum members</h3><p>Flow Enums provide a <a href="https://flow.org/en/docs/enums/using-enums/#toc-members">.members() method</a>, which returns an iterator (like Map.prototype.values) of the enum’s members.</p><pre>// Flow:<br>enum Status {<br>  Active = 0,<br>  Paused = 1,<br>  Off = 2,<br>}<br>for (const status of Status.members()) {<br>  const name = Status.getName(status); <br>  console.log(name); //=&gt; &quot;Active&quot;, &quot;Paused&quot;, &quot;Off&quot;<br>}</pre><p>TypeScript enums do not have special functionality in this regard. You can use a for-in loop to go over the members, but for number enums this will result in both the names and the values:</p><pre>// TypeScript:<br>enum Status {<br>  Active = 0,<br>  Paused = 1,<br>  Off = 2<br>}</pre><pre>for (const status in Status) {<br>  console.log(status); //=&gt; &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;Active&quot;, &quot;Paused&quot;, &quot;Off&quot;<br>}</pre><h3>Symbol enums</h3><p>Flow Enums support <a href="https://flow.org/en/docs/enums/defining-enums/#toc-symbol-enums">symbol enums</a>. Symbol enum values can never conflict with any other value in your program, since they are symbols and therefore unique. This comes with the downside that they cannot be serialized or inlined, but this is a trade-off you can choose to make:</p><pre>// Flow:<br>enum Status of symbol {<br>  Active,<br>  Paused,<br>  Off,<br>}</pre><p>TypeScript does not support symbol enums.</p><h3>Definition restrictions</h3><p>Flow Enums are more restrictive than TypeScript enums when it comes to their <a href="https://flow.org/en/docs/enums/defining-enums/">definition</a>. The general philosophy of the Flow Enums design was to start off being restrictive, and wait to see actual use-cases and requests before expanding functionality. It is always easier to loosen up constraints than tighten them up.</p><p>Unlike TypeScript, Flow Enum members must:</p><ul><li>All have the same type (no heterogeneous enums)</li><li>Be literals, if a value is specified (no arbitrary expressions)</li><li>Either have all of their values specified, or all defaulted</li><li>Have unique member values</li><li>Have their member names start with an uppercase letter (lowercase starting letters are reserved for the enum <a href="https://flow.org/en/docs/enums/using-enums/#toc-methods">methods</a> like .cast)</li></ul><p>You can read more about <a href="https://flow.org/en/docs/enums/defining-enums/">defining Flow Enums</a>.</p><h3>Inlining</h3><p>TypeScript provides “const enums”, which allow you to specify at the definition site that this enum will be inlined when using TypeScript’s supplied build system.</p><p>Flow Enums are designed to have properties that make inlining possible (e.g. member values must be literals, and the enum definition is frozen) other than for enum methods usage and symbol enums, which cannot be inlined by their nature. Rather than implement inlining in Flow, we leave the implementation of that to whatever build system you are using. We view enum inlining as an optimization performed by the build system rather than a feature of the language. Internally at Facebook we have implemented inlining for many cases of Flow Enums in our primary internal build system.</p><h3>More</h3><p>This was an overview of some of the differences between Flow Enums and TypeScript enums. Take a look at the <a href="https://flow.org/en/docs/enums/">full documentation</a> to learn more about Flow Enums.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83da2ca4a9b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/typescript-enums-vs-flow-enums-83da2ca4a9b4">TypeScript Enums vs. Flow Enums</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Flow Enums]]></title>
            <link>https://medium.com/flow-type/introducing-flow-enums-16d4239b3180?source=rss-95a4c0399e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/16d4239b3180</guid>
            <category><![CDATA[flowtype]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flow]]></category>
            <dc:creator><![CDATA[George Zahariev]]></dc:creator>
            <pubDate>Mon, 13 Sep 2021 17:40:53 GMT</pubDate>
            <atom:updated>2021-09-13T17:42:05.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcM4gHRmYHRx64mosNG2uQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@dreamypixel?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Krivec Ales</a> from <a href="https://www.pexels.com/photo/gray-rock-mountain-547115/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>As announced in an earlier <a href="https://medium.com/flow-type/clarity-on-flows-direction-and-open-source-engagement-e721a4eb4d8b">post</a>, Flow will be introducing new language features. The first one is <a href="https://flow.org/en/docs/enums/">Flow Enums</a>, an opt-in feature which allows you to define a fixed set of constants which create their own type. If you are familiar with TypeScript, you can take a look at <a href="https://medium.com/flow-type/typescript-enums-vs-flow-enums-83da2ca4a9b4">our comparison of Flow Enums and TypeScript enums</a>.</p><p>Flow Enums provide several benefits over existing enum-like patterns (like Object.freeze and string literal unions): reducing repetition by defining a value and type in one definition, enabling new functionality like a type-safe <a href="https://flow.org/en/docs/using-enums/#toc-cast">cast</a> function, enhancing safety by requiring <a href="https://flow.org/en/docs/enums/using-enums/#toc-exhaustively-checking-enums-with-a-switch">exhaustive checking</a> in switch statements, and guaranteeing good Flow performance.</p><p>At Facebook, we’ve been using Flow Enums for over a year, and have over 5,000 Flow Enums in our codebase.</p><p>The <a href="https://flow.org/en/docs/enums/">documentation</a> has complete information about how to <a href="https://flow.org/en/docs/enums/enabling-enums/">enable</a>, <a href="https://flow.org/en/docs/enums/defining-enums/">define</a> and <a href="https://flow.org/en/docs/enums/using-enums/">use</a> Flow Enums. Here is a quick overview:</p><h3>Overview</h3><p>Unlike other features in Flow, enums exist as values at runtime, as well as existing as types.</p><p>Define an<a href="https://flow.org/en/docs/enums/defining-enums/#toc-string-enums"> enum with string values</a> which mirror the member names:</p><pre>enum Status {<br>  Active,<br>  Paused,<br>  Off,<br>}</pre><p>Define an <a href="https://flow.org/en/docs/enums/defining-enums/#toc-number-enums">enum with number values</a>:</p><pre>enum Status {<br>  Active = 1,<br>  Paused = 2,<br>  Off = 3,<br>}</pre><p>Previously if using Object.freeze, you would have to define a object with values and a type separately, which is more verbose.</p><p>Access an enum member, and use the enum name as a type annotation:</p><pre>const status: Status = Status.Active;</pre><p>Previously, the type name and enum object name would be different, now we can have one name and one import for both type and value.</p><p>Safely <a href="https://flow.org/en/docs/enums/using-enums/#toc-cast">cast</a> a string to an enum member (or undefined if not a valid member):</p><pre>const couldBeStatus: Status | void = Status.cast(someString);</pre><p>Previously, you would have to create a switch statement with every enum member as a case in order to cast an arbitrary string/number to an enum value in a type-safe way.</p><p>Check an enum in <a href="https://flow.org/en/docs/enums/using-enums/#toc-exhaustively-checking-enums-with-a-switch">switch statement exhaustively</a> - we ensure you check all members:</p><pre>// ERROR: Incomplete exhaustive check: the member `Off` of enum<br>// `Status` has not been considered in check of `status`<br>switch (status) {<br>  case Status.Active: ...; break;<br>  case Status.Paused: ...; break;<br>  // We forgot to add `case: Status.Off:` here,<br>  // resulting in error above<br>}</pre><p>Flow Enums are not a syntax for union types. They are their own type, and each member of a Flow Enum has the same type. Large union types can cause performance issues, as Flow has to consider each member as a separate type. With Flow Enums, no matter how large your enum is, Flow will always exhibit good performance as it only has one type to keep track of.</p><p>Read the <a href="https://flow.org/en/docs/enums/#toc-quickstart">quickstart guide</a> for more, and the <a href="https://flow.org/en/docs/enums/defining-enums/">defining enums</a> and <a href="https://flow.org/en/docs/enums/using-enums/">using enums</a> documentation for an in-depth look.</p><h3>Enabling Flow Enums</h3><p>You can read the full <a href="https://flow.org/en/docs/enums/enabling-enums/">documentation</a> on how to enable Flow Enums in your project. In short:</p><ul><li><a href="https://flow.org/en/docs/enums/enabling-enums/#toc-upgrade-tooling">Upgrade your tooling</a> (e.g. Prettier, Babel, Flow, etc.) to support the new syntax</li><li>Add <a href="https://www.npmjs.com/package/babel-plugin-transform-flow-enums">babel-plugin-transform-flow-enums</a> to your Babel transform pipeline</li><li>Add the <a href="https://www.npmjs.com/package/flow-enums-runtime">flow-enums-runtime</a> module to your production dependencies (called from the output of the transform)</li><li>Enable in your .flowconfig by adding enums=true in the [options] section</li></ul><h3>Migrating Legacy Patterns</h3><p>You can then <a href="https://flow.org/en/docs/enums/migrating-legacy-patterns/">migrate from legacy patterns</a> in your codebase. For example, if before you had:</p><pre>const Status = Object.freeze({<br>  Active: 1,<br>  Paused: 2,<br>  Off: 3,<br>});<br>type StatusType = $Values&lt;typeof Status&gt;;<br>const status: StatusType = Status.Active;</pre><p>You can use:</p><pre>enum Status {<br>  Active = 1,<br>  Paused = 2,<br>  Off = 3,<br>}<br>const status: Status = Status.Active;</pre><p>If before you cast to the enum type like this:</p><pre>function castToStatus(input: number): StatusType | void {<br>  switch(input) {<br>    case 1: return Status.Active;<br>    case 2: return Status.Paused;<br>    case 3: return Status.Off;<br>    default: return undefined;<br>  }<br>}</pre><pre>castToStatus(x)</pre><p>You can now just use:</p><pre>Status.cast(x)</pre><h3>More</h3><p>Read the <a href="https://flow.org/en/docs/enums/">documentation</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d4239b3180" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flow-type/introducing-flow-enums-16d4239b3180">Introducing Flow Enums</a> was originally published in <a href="https://medium.com/flow-type">Flow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>