Member-only story
Intersection Types and JavaScript Type Checking With Flow
A look at the intersection of object types
Flow is a type checker made by Facebook for checking JavaScript data types. It has many built-in data types we can use to annotate the types of variables and function parameters.
In this piece, we’ll look at how to use intersection types to create variables that accept a combination of multiple types.
Defining Intersection Types
We can create intersection types by separating multiple types with an &
sign as follows:
Type1 & Type2 & ... & TypeN
We can also break the expression above into multiple lines with the leading &
sign:
type Bar =
& Type1
& Type2
& ...
& TypeN
Also, we can create intersection types from other intersection types:
type A = Type1 & Type2;
type B = Type3 & Type4;
type Foo = A & B;
Properties of Intersection Types
When we call a function that accepts an intersection type, we must pass in data that has all of those types. But inside the function, we can treat them as being one of the types in the intersection type.
For example, if we define the following function:
type A = { a: number };
type B = { b: boolean };
type C = { c: string };
function foo(value: A & B & C) {
}
Then we can treat value
as having to be any one of A
, B
and C
, as follows:
function foo(value: A & B & C) {
let a: A = value;
let b: B = value;
let c: C = value;
}
Impossible Intersection Types
We can create intersection types that are impossible. For example, we can create a type that’s an intersection of string
and boolean
, as follows:
type StringBoolean = string & boolean;
This type is useless since no value can be both a string and a boolean, so we can’t assign anything to it.