openapi-typescript
openapi-typescript copied to clipboard
immutable option and readonly arrays
Description
I've been using 7.0.0-next.7 and it is working fine with --immutable, except it would be nice for the arrays to be readonly as well, so that the types are fully immutable. As it currently stands, even with immutable, you can still mutate any arrays. That is,
"Test": {
"type": "object",
"properties": {
"Foo": {
"type": "array",
"items": {
"type": "string"
}
}
}
Currently generates
Test: {
readonly Foo: string[];
}
While the property foo is immutable, the array stored inside the foo property can be mutated.
Proposal
Generate instead
Test: {
readonly Foo: readonly string[];
}
or
Test: {
readonly Foo: ReadonlyArray<string>;
}
To typescript, the ReadonlyArray or readonly string[]
are equivalent, see docs
Checklist
- [X] I’m willing to open a PR for this (see CONTRIBUTING.md)
Looks like it is this line in schema-object, but I am unfamiliar with the typescript factory API. I was trying to search for some documentation, is there any documentation of the typescript factory API?
Would love a PR for this! My suggestion is to first write the failing test in test/transform/schema-object/array.test.ts
for the expected syntax, then get it to pass (without getting the other tests to fail).
I am unfamiliar with the typescript factory API. I was trying to search for some documentation, is there any documentation of the typescript factory API?
Not really; it’s all pretty much trial-and-error. That’s why the granular unit tests exist for every function; it makes it easier to start small when building the AST. Then work upwards until you’re at the entire schema level. Fortunately, the TS factory API has good types (as one would hope), so it also helps guide you in the right direction if you look at the function signatures (and of course, copy from other parts of the code)
Our codebase uses ReadyonlyArray
s wherever it can and casting the data explicitly partially defeats the purpose of generating the types. This suggested change would make everything much more pleasant.
Is there actually any reason why the types should be ever be mutable?
Is there actually any reason why the types should be ever be mutable?
That’s a great question. Requests tend to be where readonly structures become cumbersome. Agree for most usecases responses can and should be immutable. But also depending on how you write your code, when you have to pass part of a response into another request, but maybe have to tweak one thing, it can also introduce boilerplate over typesafety. For all these little papercuts it’s recommended, and supported, but not enforced by default as it’s overreaching for some people.
Fixed! Will be available in the next @next
release.
Thanks, I just tested the latest git with my schema and it works, producing readonly arrays.