json-schema-to-typescript
json-schema-to-typescript copied to clipboard
Support generics
Can you support generics? Like generating from this:
{
"title": "TGenericNumber",
"type": { "$ref": "#/definitions/iarg", "generics": ["number", "string"] },
"definitions": {
"iarg": {
"title": "IArg<T, R>",
"properties": {
"key": { "type": "T" },
"value": { "type": "R" }
}
}
}
}
to this:
export interface IArg<T, R> { key: T, value: R };
export type TGeneric = IArg<number, string>;
This is an interesting idea. I guess there are 2 parts:
- Inferring that property types are generic - We can either:
a. Assume that types that begin with a capital letter are generic
b. Use an explicit JSON-Schema extension, eg.
"genericType": "T"c. Don't special case, and let the consumer handle it (as in your example) - Binding concrete types to generic types: a. Use an explicit JSON-Schema extension (as in your example) b. ???
Explicit is always better than implicit, but for first part I was assuming that it will infer types from title <T, R>
Inferring from title is too unstructured for my taste, and makes parts 1 and 2 above asymmetrical. Also, someone might for some reason have "IArg<T, R>" as a title, but not intend it as a generic interface. I'd go for explicit all the way through (options 1b and 2a). What do you think?
maybe you are right
@bcherny Yes, you are right explicit is better here too
Any update on this new feature would be great to have and also add conditionals types
@joseSantacruz What’s your use case for generic and conditional types in JSON-Schema?
My use case (and the reason for my fork) is opaque containers. For example, our application has a lot of encrypted data, so our API frequently sends something of type CryptoContainer with predictable fields for ciphertext, algorithm options, &c., but this doesn’t provide information about what is encrypted. Hence, I added generic parameters like CryptoContainer<T> so that, though this won’t be enforced by JSON schema validation, at least the server and client can agree on the protocol.
That's necessary for container-contracts: events, commands, etc. We faced same problem with protobuffs and there is only workaround to use something like Any, but I don't have an idea how to do same with json-schema. It's really hard to support DTOs like CutstomerEvent, ApplicationEvent, PaymentEvent instead of Event<T>, for example Event<Customer>.
a rather simple way of allowing use of generics is to patch the regex in toSafeString() in src/utils.ts to also allow "<" and ">" being part of TS identifier and then use e.g.
title: Typename<Generic>