Class Types

Typing classes and using classes as types

JavaScript classes in Flow operate both as a value and a type.

You write classes the same way you would without Flow, but then you can use the name of the class as a type.

1
2
3
4
5
class MyClass {
  // ...
}

let myInstance: MyClass = new MyClass();

This is because classes in Flow are nominally typed.

Class Syntax

Classes in Flow are identical to normal JavaScript classes, but with added types.

Class Methods

Just like in functions, class methods can have annotations for both parameters (input) and returns (output).

1
2
3
class MyClass {
  method(value: string): number { /* ... */ }
}
Class Fields (Properties)

Whenever you want to use a class field in Flow you must first give it an annotation.

1
2
3
4
5
6
7
// @flow
class MyClass {
  method() {
    // $ExpectError
    this.prop = 42; // Error!
  }
}
property `prop` Property not found in MyClass

Fields are annotated within the body of the class with the field name followed by a colon : and the type.

1
2
3
4
5
6
7
// @flow
class MyClass {
  prop: number;
  method() {
    this.prop = 42;
  }
}

Flow also supports using the class properties syntax.

1
2
3
class MyClass {
  prop = 42;
}

When using this syntax, you are not required to give it a type annotation. But you still can if you need to.

1
2
3
class MyClass {
  prop: number = 42;
}
Class Generics

Classes can also have their own generics.

1
2
3
4
5
6
class MyClass<A, B, C> {
  property: A;
  method(val: B): C {
    // ...
  }
}

Class generics are parameterized. When you use a class as a type you need to pass parameters for each of its generics.

1
2
3
4
5
6
7
8
// @flow
class MyClass<A, B, C> {
  constructor(arg1: A, arg2: B, arg3: C) {
    // ...
  }
}

var val: MyClass<number, boolean, string> = new MyClass(1, true, 'three');