How to do it…

It so happens that Flow provides two ways of specifying types: the way that we have been using so far, with extra type notations, and another more verbose one, through the comments. Of course, JS doesn't know about type definitions, so the first style won't work unless we do extra work (as we'll see) but using comments is totally safe.

To define types with comments, all Flow specific definitions must be enclosed in comments starting with /*: (note the extra colon) and finishing with the usual */, for simple basic types, or /*:: and */ for everything else. We can revisit some examples we saw earlier in Chapter 2, Using JavaScript Modern Features. Simple cases are as follows:

// Source file: src/flowcomments.js

let someFlag /*: boolean */;
let greatTotal /*: number */;
let firstName /*: string */;

function toString(x /*: number */) /*: string */ {
return String(x);
}

let traffic /*: "red" | "amber" | "green" */;

// continues...

More complex definitions, including optional parameters, types and opaque types, class attributes, and so on, require the longer comments:

// ...continued

/*::

type pair<T> = [T, T];
type pairOfNumbers = pair<number>;
type pairOfStrings = pair<string>;

type simpleFlag = number | boolean;

type complexObject = {
id: string,
name: string,
indicator: simpleFlag,
listOfValues: Array<number>
};
*/

class Person {
/*::
first: string;
last: string;
*/

constructor(first /*: string */, last /*: string */) {
this.first = first;
this.last = last;
}

// ...several methods, snipped out
}

// continues...

You can also export and import data types:

// ...continued

/*::

import type { dniType, nameType } from "./opaque_types";
*/

/*::
export type { pairOfNumbers, pairOfStrings };
*/
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.152.58