An easier way to force typed immutable data structures to be forced?

Providing a data structure with vanilla objects and a JS stream is easy:

type ExampleObjType = {
  key1: number,
  key2: string
};

const obj: ExampleObjType = {
  key1: 123,
  key2: '123'
};

This seems to require an unnecessarily large number of templates to provide a similar structure in an immutable:

type TestSpec = {
  key1: number,
  key2: string,
};

const TestRecord = Record({
  key1: 0,
  key2: '',
});

const record: TestSpec & Record<TestSpec> = new TestRecord({
  key1: 123,
  key2: '123',
});

In addition, this structure has some basic disadvantages:

  • Force Defaults
  • Initialization does not force invalid keys, only on access

Ideally, I could use Immutable.Mapsomething like this:

type TestSpec = Map<{key1: number, key2: number}>;

const testMap: TestSpec = Map({
  key1: 123,
  key2: '123',
});

However, the current implementation allows only key type and values ​​to be entered. I could restrict the type of key using something like hokey like type Key = 'key1' | 'key2', but I still don't need to explicitly enter values ​​for the key.

, ? , , , Redux.

+4
1

immutable.Record() . , , any. , , TestRecord . , , !

:

interface TestSpec {
  constructor(defaults: $Shape<TestSpec>): void,
  key1: number,
  key2: string,
};

const TestRecord: Class<TestSpec> = Record({
  key1: 0,
  key2: '',
});

Class<TestSpec> - , TestSpec. TestSpec, Flow , obj , new TestRecord(obj).

(: $Shape<TestSpec> - , . , {key1?: number, key2?: string})

new TestRecord({key1: 123,  key2: '123'}); // OK
new TestRecord({key1: 123}); // OK
new TestRecord({key2: '123'}); // OK

new TestRecord({key2: 123}); // Error number -> string
new TestRecord({key1: '123'}); // Error string -> number
new TestRecord({key1: 123,  key2: '123', key3: 'blah'}); // Error unknown property key3

Flow ,

const record = new TestRecord({key1: 123,  key2: '123'});
(record.key1: string); // Error number -> string
(record.key2: number); // Error string -> number

flowtype.org/try

+6

Source: https://habr.com/ru/post/1650721/


All Articles