JSON property value type
rpidburachynskyi opened this issue · comments
Library contains good type Primitive
, its very useful, it's good idea to have the same type but for types from JSON, something like that: type JSONFieldType = string | number | boolean | null | Record<string, JSONFieldType>;
(but with better name)
@kitsoRik thank you again for the good suggestion!
At the moment I'm preparing for the conference and will be back next week!
For me the plan sounds good, I really like the idea and most probably we will start adding it soon
cc @krzkaczor
@Beraliv Yeah, this is a good package that I install in all projects where I use TypeScript, and I would like to have there all common types. That's not a problem for me (about your busy status). Anyway, I need this type in my current project and I just put it in my types folder.
FYI, now it looks like this:
export type JsonFieldType =
| string
| number
| boolean
| null
| { [path: string]: JsonFieldType }
| JsonFieldType[];
I'm not sure this is finished implementation, so you need to test all cases.
Hi. Regarding my implementation above, found a strange behaviour with inherited classes.
export type JsonFieldType =
| string
| number
| boolean
// | undefined // uncomment to fix
| null
| { [path: string]: JsonFieldType }
| JsonFieldType[];
abstract class A {
method(): JsonFieldType {
if(Math.random() > 0.5) {
return { q: 1 };
}
return { q: 1 };
}
}
class B extends A {
method()/*: JsonFieldType */ { // uncomment to fix
if(Math.random() > 0.5) {
return { q: 1 };
}
return { w: 1 };
}
}
Probably - good way to add undefined
to the union, or no, IDK.
Hmm, that's weird
I tried it here – https://tsplay.dev/WPx85W and doesn't have any issues
What TypeScript do you have?
Hmm, that's weird
I tried it here – https://tsplay.dev/WPx85W and doesn't have any issues
What TypeScript do you have?
Yeah, because you uncommented some strings. It works fine without undefined
(only with implicitly defined return type of method)
Hmm, that's weird
I tried it here – https://tsplay.dev/WPx85W and doesn't have any issues
What TypeScript do you have?Yeah, because you uncommented some strings. It works fine without
undefined
(only with implicitly defined return type of method)
Ah, sorry, I needed to have it without uncommenting
Also this can be connected with the future implementation of JsonFieldType
– #276
Also found interesting implementation here – microsoft/TypeScript#1897 (comment)
Hey @rpidburachynskyi! I'm planning to include it in the next minor change, would you be interested in having this type now?
I'm planning to implement JsonPrimitive
, JsonObject
, JsonArray
and JsonValue
based on https://www.rfc-editor.org/rfc/rfc8259#section-3