Skip to content

Commit

Permalink
Fix Jsonify to look deeper (#498)
Browse files Browse the repository at this point in the history
  • Loading branch information
skarab42 committed Oct 19, 2022
1 parent f24821b commit e11d30b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion source/jsonify.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export type Jsonify<T> =
// Any object with toJSON is special case
? T extends {toJSON(): infer J} ? (() => 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
: Jsonify<J> // Maybe if we look a level deeper we'll find a JsonValue
// Instanced primitives are objects
: T extends Number ? number
: T extends String ? string
Expand Down
26 changes: 26 additions & 0 deletions test-d/jsonify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,37 @@ class NonJsonWithToJSON {
};
}
}

const nonJsonWithToJSON = new NonJsonWithToJSON();
expectNotAssignable<JsonValue>(nonJsonWithToJSON);
expectAssignable<JsonValue>(nonJsonWithToJSON.toJSON());
expectAssignable<Jsonify<NonJsonWithToJSON>>(nonJsonWithToJSON.toJSON());

class NonJsonWithToJSONWrapper {
public inner: NonJsonWithToJSON = nonJsonWithToJSON;
public override = 42;

public toJSON() {
const stringOverride = 'override';

return {
override: stringOverride,
inner: this.inner,
innerDeep: {inner: this.inner},
};
}
}

expectNotAssignable<JsonValue>(new NonJsonWithToJSONWrapper());

type InnerFixture = {fixture: Array<[string, number]>};

expectType<{
override: string;
inner: InnerFixture;
innerDeep: {inner: InnerFixture};
}>({} as Jsonify<NonJsonWithToJSONWrapper>);

class NonJsonWithInvalidToJSON {
public fixture = new Map<string, number>([['a', 1], ['b', 2]]);

Expand Down

0 comments on commit e11d30b

Please sign in to comment.