Starcounter-Jack / JSON-Patch

Lean and mean Javascript implementation of the JSON-Patch standard (RFC 6902). Update JSON documents using delta patches.
MIT License
1.79k stars 215 forks source link

Discussion about Typescript typings #263

Closed tbinna closed 3 years ago

tbinna commented 3 years ago

I just started testing this library and I am trying to make sense of the typings. For example:

applyOperation<T>(document: T, operation: Operation, ...): OperationResult<T>

Ref: https://github.com/Starcounter-Jack/JSON-Patch/blob/2ad6af4f79af8db0516cca7089ce55295ef01bac/src/core.ts#L182

This function takes a document of type T and returns a result of OperationResult<T>. This says that the input document and output document are structurally the same which seems quite strange to me. An operation can transform the document in ways such that the output document has a completely different structure compared to the input.

I am wondering if applyOperation instead would have to be typed like this:

applyOperation<A, B>(document: A, operation: Operation, ...): OperationResult<B>

The only workaround I see with the existing typing would be to declare an intersection type A & B and pass that as the type parameter for T. But that is less than ideal because it would not be correct.

Any opinions or ideas on this?

tbinna commented 3 years ago

Just wanted to update my post above with some insights. The way to think about T is that T is not just any type. T is any JSON compatible type. I.e. one of the following:

If Typescript had a type Json that describes all acceptable JSON values applyOperation would look like this:

applyOperation<Json>(document: Json, operation: Operation, ...): OperationResult<Json>

I think this makes sense to me now. I will close this issue because I think there is currently no way to better describe any JSON compatible type in Typescript.

wikked1 commented 3 years ago

I'm also hoping TypeScript might add a typedef for JsonObject and JsonValue, but here are some you could import or copy from other open source projects if you wanted to:

https://github.com/sindresorhus/type-fest/blob/5621e9e3f34c364a58b5dd73f7d4df89ce6e4a0d/source/basic.d.ts#L32 https://github.com/angular/angular-devkit-core-builds/blob/d9f9477ef7f966fc2ee7aedd47b3a9cb0ae31edf/src/json/interface.d.ts#L39 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/json-schema/index.d.ts#L258 https://github.com/puppeteer/puppeteer/blob/f1b46ab5faa262f893c17923579d0cf52268a764/src/common/EvalTypes.ts#L60