openapi-typescript-codegen
openapi-typescript-codegen copied to clipboard
introducing `OmitReadonly` type to resolve required + readonly/writeonly properties
closes #432
Pretext:
Say there are 2 properties to a model id and name. Creating a model instance (POST) requires only name to be posted and id would be a readonly property. Generated type would be
type Model {
readonly id: number;
name: string;
}
To create an instance of Model for POST, we should be able to pass {name: "john"}
Generated services look like: createMode(model: Model) {...}, which do not accept an object with just name property.
Solution:
This PR aims to solve this issue by adding a type modifier, so effectively generated service code looks like: createMode(model: OmitReadOnly<Model>) {...} which strips off any readonly properties and allows passing an object with just the name property.
More about OmitReadonly:
- it omits readonly properties from an object
- it infers the original type in case of passed type is not an
object - it is applied to parameters for "POST", "PUT" or "PATCH" operations and only if it is a "reference" type
Implementation based on https://github.com/ferdikoomen/openapi-typescript-codegen/issues/432#issuecomment-1019519372 by @sweethuman
Please change the OmitReadonly imports to type imports. Vite will complain otherwise. Thank you.
https://github.com/ferdikoomen/openapi-typescript-codegen/pull/1145/files#diff-33d2b8dc9fd33ef2b353540e2ff031e54952e1013569382346cab750d11f9da2R33
We desperately need this. =)
@tiholic Any chance we can get the type import fixed? @ferdikoomen Can we get this merged after?
I'm happy to help. Let me know if I can support in any way.
@aaronschif @jeremyzahner import converted to a type import
@ferdikoomen I believe this can be prioritised now?
@tiholic @aaronschif @demo-exe for the time being, you can use https://www.npmjs.com/package/@jshmrtn/openapi-typescript-codegen until @ferdikoomen can have a look.
Any chance to get this merged?
@tiholic this is interesting. It appears that openapi-typescript-codegen is marking readonly fields as optional, which I think solves the problem you outlined above (not being able to just do createMode({.name }: Model) {...}
We are facing almost the opposite problem - because these readonly fields are optional, we are getting the response model type containing things like optional ids, which we definitely don't want
Bumping @giopetris's request – would it be possible to get this merged?
@mrlubos Maybe this could be merged into your fork?
@tajnymag do you mind opening an issue in our repository? I'd like to solve this with write-only too, this pull request seems to work only for read-only