Skip to content

Commit

Permalink
Improve type infererence for fromJS (#1927)
Browse files Browse the repository at this point in the history
Co-authored-by: khai96_ <hvksmr1996@gmail.com>
  • Loading branch information
jdeniau and KSXGitHub committed Feb 3, 2023
1 parent d2d5819 commit 5e2379b
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
29 changes: 28 additions & 1 deletion type-definitions/immutable.d.ts
Expand Up @@ -5160,12 +5160,39 @@ declare namespace Immutable {
*/
function fromJS(
jsValue: unknown,
reviver?: (
reviver: (
key: string | number,
sequence: Collection.Keyed<string, unknown> | Collection.Indexed<unknown>,
path?: Array<string | number>
) => unknown
): Collection<unknown, unknown>;
function fromJS<JSValue>(
jsValue: JSValue,
reviver?: undefined
): FromJS<JSValue>;

type FromJS<JSValue> = JSValue extends FromJSNoTransform
? JSValue
: JSValue extends Array<any>
? FromJSArray<JSValue>
: JSValue extends {}
? FromJSObject<JSValue>
: any;

type FromJSNoTransform =
| Collection<any, any>
| number
| string
| null
| undefined;

type FromJSArray<JSValue> = JSValue extends Array<infer T>
? List<FromJS<T>>
: never;

type FromJSObject<JSValue> = JSValue extends {}
? Map<keyof JSValue, FromJS<JSValue[keyof JSValue]>>
: never;

/**
* Value equality check with semantics similar to `Object.is`, but treats
Expand Down
35 changes: 35 additions & 0 deletions type-definitions/ts-tests/from-js.ts
@@ -0,0 +1,35 @@
import { fromJS, List, Map } from 'immutable';

{
// fromJS

// $ExpectType Collection<unknown, unknown>
fromJS({}, (a: any, b: any) => b);

// $ExpectType string
fromJS('abc');

// $ExpectType List<number>
fromJS([0, 1, 2]);

// $ExpectType List<number>
fromJS(List([0, 1, 2]));

// $ExpectType Map<"b" | "a" | "c", number>
fromJS({a: 0, b: 1, c: 2});

// $ExpectType Map<string, number>
fromJS(Map({a: 0, b: 1, c: 2}));

// $ExpectType List<Map<"a", number>>
fromJS([{a: 0}]);

// $ExpectType Map<"a", List<number>>
fromJS({a: [0]});

// $ExpectType List<List<List<number>>>
fromJS([[[0]]]);

// $ExpectType Map<"a", Map<"b", Map<"c", number>>>
fromJS({a: {b: {c: 0}}});
}

0 comments on commit 5e2379b

Please sign in to comment.