Private Object Properties Using Flow’s Opaque Type Aliases

Jordan Brown
Flow
Published in
2 min readAug 25, 2017

--

In the last few weeks, a proposal for private class fields in Javascript reached stage 3. This is going to be a great way to hide implementation details away from users of your classes. However, locking yourself in to an OOP style of programming is not always ideal if you prefer a more functional style. Let’s talk about how you can use Flow’s opaque type aliases to get private properties on any object type.

The Power of Subtyping

If you’re familiar with Flow’s opaque type aliases, you may recall that they allow subtyping constraints:

private.js:// @flowopaque type Integer: number = number;

This subtyping constraint tells Flow that it can be used as a number even when you’re outside of private.js.

In Flow, we use width subtyping to determine if an object is a subtype of another. Simply put, if an object A has at least all of the properties of object B, then A is a subtype of B.

We can take advantage of this subtyping rule to create an object type that hides properties outside of the file in which it is defined. All you have to do is exclude any properties you want private in the subtyping constraint:

hide.js://@flowexport opaque type Private: {
x: number,
} = {
x: number,
yPrivate: number,
};

Inside the file, accessing yPrivate is totally fine:

hide.js:/* ... */function touchesY(a: Private) {
a.yPrivate = 0; // Ok
}

But outside of the file, you cannot access yPrivate!

imports.js:// @flowimport type {Private} from './hide';function cantTouchY(a: Private) {
a.x = 3; // Ok
a.yPrivate = 0; // Error: `yPrivate` not found on `a`!
}

Whats the Difference?

Though we can create private fields in the type system with opaque types, they are still slightly different. Private fields are private to the class whereas private properties are private to the file. This means that more things may have access to the private properties than if you had a private field on a class.

Want to read more about Flow’s opaque type aliases? Check out the post we put out when they were released here. They are also documented on the Flow website here.

Are you building cool things with Flow or opaque type aliases? We want to hear from you! Send a tweet to flowtype on Twitter so the whole community may celebrate your efforts to make writing JavaScript delightful.

--

--