typescript-generator
typescript-generator copied to clipboard
Feature suggestion: readOnlyArrays as configuration option
In addition to the existing configuration option "declarePropertiesAsReadOnly" it would be great to have an option "readOnlyArrays" which would generate:
ReadonlyArray<MyType>
instead of
MyType[]
for all properties that are arrays. So unwanted Mutation can be avoided.
This also could be candidate for using mapped types and conditional types in TypeScript.
With conditional types it will be possible to have DeepReadonly<T>
generic type.
Same advantages and disadvantages as I mentioned in #217 applies here. For me pros would really be to have 2 variants of classes for read and write like this:
interface Client {
createMyType(myType: MyType): void;
readMyType(): DeepReadonly<MyType>;
updateMyType(myType: MyType): DeepReadonly<MyType>;
}
This would be an option. But I think the opportunity to generate Arrays readonly directly would be a useful feature as it goes hand in hand with the opportunity to create properties readonly without having to use mapped types.
What about MyType[][]
? Should this become ReadonlyArray<ReadonlyArray<MyType>>
?
And what about { [index: string]: MyType[] }
created from Map<List<MyType>>
in Java?
Should also objects (created from Map
) have read-only index signatures like this: { readonly [index: string]: ReadonlyArray<MyType> }
?
It would probably make more sense to do this for all "container" types (arrays and also objects with index signature).
I see this feature as an opportunity to make sure the generated types can't be mutated.
Following this I think these container types should be generated like you suggested.
Heads up, with TypeScript 3.4, there is a concise syntax for readonly arrays: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#a-new-syntax-for-readonlyarray
Maybe declarePropertiesAsReadOnly
could add the readonly array modifier to array types? This might be a breaking change but in most cases exactly what you want.