Skip to content

Commit

Permalink
Jsonify: Allow partial types (#312)
Browse files Browse the repository at this point in the history
  • Loading branch information
bbrk24 committed Jan 6, 2022
1 parent b9ace21 commit 600f0c2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion source/jsonify.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,6 @@ type Jsonify<T> =
? (() => J) extends (() => JsonValue) // Is J assignable to JsonValue?
? J // Then T is Jsonable and its Jsonable value is J
: never // Not Jsonable because its toJSON() method does not return JsonValue
: {[P in keyof T]: Jsonify<T[P]>} // It's an object: recursive call for its children
: {[P in keyof T]: Jsonify<Required<T>[P]>} // It's an object: recursive call for its children
: never // Otherwise any other non-object is removed
: never; // Otherwise non-JSONable type union was found not empty
29 changes: 28 additions & 1 deletion test-d/jsonify.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {expectAssignable, expectNotAssignable} from 'tsd';
import {expectAssignable, expectNotAssignable, expectType} from 'tsd';
import {Jsonify, JsonValue} from '..';

interface A {
Expand Down Expand Up @@ -122,3 +122,30 @@ class NonJsonWithInvalidToJSON {
const nonJsonWithInvalidToJSON = new NonJsonWithInvalidToJSON();
expectNotAssignable<JsonValue>(nonJsonWithInvalidToJSON);
expectNotAssignable<JsonValue>(nonJsonWithInvalidToJSON.toJSON());

// Test that optional type members are not discarded wholesale.
interface OptionalPrimitive {
a?: string;
}

interface OptionalTypeUnion {
a?: string | (() => any);
}

interface OptionalFunction {
a?: () => any;
}

interface NonOptionalTypeUnion {
a: string | undefined;
}

declare const jsonifiedOptionalPrimitive: Jsonify<OptionalPrimitive>;
declare const jsonifiedOptionalTypeUnion: Jsonify<OptionalTypeUnion>;
declare const jsonifiedOptionalFunction: Jsonify<OptionalFunction>;
declare const jsonifiedNonOptionalTypeUnion: Jsonify<NonOptionalTypeUnion>;

expectType<{a?: string}>(jsonifiedOptionalPrimitive);
expectType<{a?: never}>(jsonifiedOptionalTypeUnion);
expectType<{a?: never}>(jsonifiedOptionalFunction);
expectType<{a: never}>(jsonifiedNonOptionalTypeUnion);

0 comments on commit 600f0c2

Please sign in to comment.