Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jsonify: Allow partial types #312

Merged
merged 3 commits into from
Jan 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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);