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: add jump to definition and any support #519

Merged
merged 21 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from 6 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
135 changes: 99 additions & 36 deletions source/jsonify.d.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
import type {JsonPrimitive, JsonValue} from './basic';
import type {EmptyObject} from './empty-object';
import type {Merge} from './merge';
import type {NegativeInfinity, PositiveInfinity} from './numeric';
import type {Simplify} from './simplify';
import type {TypedArray} from './typed-array';

/*
* `any` is the only type that can let you equate `0` with `1`
* See https://stackoverflow.com/a/49928360/1490091
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
*/
type IsAny<T> = 0 extends 1 & T ? true : false;
sachinraja marked this conversation as resolved.
Show resolved Hide resolved

// Note: The return value has to be `any` and not `unknown` so it can match `void`.
type NotJsonable = ((...args: any[]) => any) | undefined | symbol;

/** JSON serialize [tuples](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) */
type JsonifyTuple<T extends [unknown, ...unknown[]]> = {
[k in keyof T]: T[k] extends NotJsonable ? null : Jsonify<T[k]>;
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
};

type FilterJsonableKeys<T extends object> = {
[Key in keyof T]: T[Key] extends NotJsonable ? never : Key;
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
}[keyof T];

/** JSON serialize objects (not including arrays) and classes */
type JsonifyObject<T extends object> = {
[k in keyof Pick<T, FilterJsonableKeys<T>>]: Jsonify<T[k]>;
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
};

// Returns never if the key or property is not jsonable without testing whether the property is required or optional otherwise return the key.
type BaseKeyFilter<Type, Key extends keyof Type> = Key extends symbol
? never
Expand All @@ -16,17 +36,53 @@ type BaseKeyFilter<Type, Key extends keyof Type> = Key extends symbol
? never
: Key;

// Returns never if the key or property is not jsonable or optional otherwise return the key.
type RequiredKeyFilter<Type, Key extends keyof Type> = undefined extends Type[Key]
? never
: BaseKeyFilter<Type, Key>;
/**
* Returns the required keys.
*/
type FilterDefinedKeys<TObject extends object> = Exclude<
{
[TKey in keyof TObject]: IsAny<TObject[TKey]> extends true
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
? TKey
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
: undefined extends TObject[TKey]
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
? never
: TObject[TKey] extends undefined
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
? never
: BaseKeyFilter<TObject, TKey>;
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
}[keyof TObject],
undefined
>;

// Returns never if the key or property is not jsonable or required otherwise return the key.
type OptionalKeyFilter<Type, Key extends keyof Type> = undefined extends Type[Key]
? Type[Key] extends undefined
/**
* Returns the optional keys.
*/
type FilterOptionalKeys<TObject extends object> = Exclude<
{
[TKey in keyof TObject]: IsAny<TObject[TKey]> extends true
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
? never
: BaseKeyFilter<Type, Key>
: never;
: undefined extends TObject[TKey]
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
? TObject[TKey] extends undefined
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
? never
: BaseKeyFilter<TObject, TKey>
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
: never;
}[keyof TObject],
undefined
>;

/*
* For an object T, if it has any properties that are a union with `undefined`,
* make those into optional properties instead.
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
*
* Example: { a: string | undefined} --> { a?: string}
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
*/
type UndefinedToOptional<T extends object> = Simplify<
{
// Property is not a union with `undefined`, keep as-is
[Key in keyof Pick<T, FilterDefinedKeys<T>>]: T[Key];
} & {
// Property _is_ a union with `defined`. Set as optional (via `?`) and remove `undefined` from the union
[k in keyof Pick<T, FilterOptionalKeys<T>>]?: Exclude<T[k], undefined>;
sachinraja marked this conversation as resolved.
Show resolved Hide resolved
}
>;

/**
Transform a type to one that is assignable to the `JsonValue` type.
Expand Down Expand Up @@ -85,29 +141,36 @@ const timeJson = JSON.parse(JSON.stringify(time)) as Jsonify<typeof time>;

@category JSON
*/
export type Jsonify<T> =
// Check if there are any non-JSONable types represented in the union.
// Note: The use of tuples in this first condition side-steps distributive conditional types
// (see https://github.com/microsoft/TypeScript/issues/29368#issuecomment-453529532)
[Extract<T, NotJsonable | bigint>] extends [never]
? T extends PositiveInfinity | NegativeInfinity ? null
: T extends JsonPrimitive ? T // Primitive is acceptable
: T extends object
// 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
: 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
: T extends Boolean ? boolean
: T extends Map<any, any> | Set<any> ? EmptyObject
: T extends TypedArray ? Record<string, number>
: T extends any[]
? {[I in keyof T]: T[I] extends NotJsonable ? null : Jsonify<T[I]>}
: Merge<
{[Key in keyof T as RequiredKeyFilter<T, Key>]: Jsonify<T[Key]>},
{[Key in keyof T as OptionalKeyFilter<T, Key>]?: Jsonify<Exclude<T[Key], undefined>>}
> // Recursive call for its children
: never // Otherwise any other non-object is removed
: never; // Otherwise non-JSONable type union was found not empty
export type Jsonify<T> = IsAny<T> extends true
? any
: T extends PositiveInfinity | NegativeInfinity
? null
: T extends JsonPrimitive
? T
: // Instanced primitives are objects
T extends Number
? number
: T extends String
? string
: T extends Boolean
? boolean
: T extends Map<any, any> | Set<any>
? EmptyObject
: T extends TypedArray
? Record<string, number>
: T extends NotJsonable
? never // Non-JSONable type union was found not empty
: // 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
: Jsonify<J> // Maybe if we look a level deeper we'll find a JsonValue
: T extends []
? []
: T extends [unknown, ...unknown[]]
? JsonifyTuple<T>
: T extends ReadonlyArray<infer U>
? Array<U extends NotJsonable ? null : Jsonify<U>>
: T extends object
? JsonifyObject<UndefinedToOptional<T>> // JsonifyObject recursive call for its children
: never; // Otherwise any other non-object is removed
10 changes: 10 additions & 0 deletions test-d/jsonify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,3 +312,13 @@ type ExpectedAppDataJson = {
declare const response: Jsonify<AppData>;

expectType<ExpectedAppDataJson>(response);

expectType<any>({} as Jsonify<any>);

declare const objectWithAnyProperty: Jsonify<{
a: any;
}>;
expectType<{a: any}>(objectWithAnyProperty);

declare const objectWithAnyProperties: Jsonify<Record<string, any>>;
expectType<Record<string, any>>(objectWithAnyProperties);