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
JsonObject doesn't allow optionals #64
Comments
We could also add |
@SamVerschueren I think it's weird to add |
Adding |
Then, how about simply make all the keys optional? @SamVerschueren it's pretty clear in this way I think. |
By doing |
@SamVerschueren Nope you can do EDIT: weirdly, |
Another thing with The reason is that interface Unicorn extends JsonObject {
unicorn: string;
rainbow: string;
} So now we can create objects following this contract const unicorn: Unicorn = {
unicorn: '🦄',
rainbow: '🌈'
}; But because I made quite a few changes to the // Made all these types generic
type JsonObject<T = any> = {[key: string]: JsonValue<T>};
interface JsonArray<T = any> extends Array<JsonValue<T>> { }
type JsonValue<T = any> = string | number | boolean | null | Pick<JsonObject<T>, Extract<keyof T, string>> | JsonArray<T>;
// EXAMPLE
interface Unicorn {
unicorn: string;
rainbow: string;
}
const unicorn: Unicorn = {
unicorn: '🦄',
rainbow: '🌈'
};
const jsonObject: JsonObject<Unicorn> = unicorn; It will fail if you change the This works much better than using I'm not saying that these changes should be made to |
Is there a way we can make it not have an index signature?
Are you using your generic JSON type as input type or return type? |
I want to type something as
JsonObject
, because the interface defines a request from an API.So then I use
extends JsonObject
, but my API has some optionals.The compiler will fail with
The reasoning behind this is that
undefined
is not serializable and doesn't exist in JSON. But how would someone solve this issue? Or should we change something in the JSON definitions oftype-fest
?A possible solution would be to allow
undefined
inJsonObject
.This allows me to add optionals to something which is a
JsonObject
.To me, this kinda makes sense because
JSON.stringify({unicorn: '🦄', rainbow: undefined})
results in{"unicorn":"🦄"}
, thus allowingundefined
in JSON like objects.The text was updated successfully, but these errors were encountered: