how to type Record classes and instances?

1k Views Asked by At

I understand that Record creates a new class. Why then does the following typecheck in Flow:

const Person  = Record({fname       : null, lname: null});
const Person2 = Record({fnameMANGLED: null, lname: null});        
const p : Person2 = new Person({fname: 'joe', lname: 'doe'}); // shouldn't Flow complain?

In contrast, when using ordinary classes, the following doesn't typecheck (as expected):

class A{constructor() {}};
class B{constructor() {}};        
const a: A = new A();
2

There are 2 best solutions below

0
On

It's because in the current type definitions of immutable JS, Record factory constructor returns any.

If you uncomment the line /*T & Record<T>*/ it catches the error as expected.

0
On

As of v4.0.0-rc.5 they added types RecordOf<T> and RecordFactory<T>.

Here is a snippet from the docs on how to use these flow types.

import type { RecordFactory, RecordOf } from 'immutable';

// Use RecordFactory<TProps> for defining new Record factory functions.
type Point3DProps = { x: number, y: number, z: number };
const makePoint3D: RecordFactory<Point3DProps> = Record({ x: 0, y: 0, z: 0 });
export makePoint3D;

// Use RecordOf<T> for defining new instances of that Record.
export type Point3D = RecordOf<Point3DProps>;
const some3DPoint: Point3D = makePoint3D({ x: 10, y: 20, z: 30 });