typescript-generator icon indicating copy to clipboard operation
typescript-generator copied to clipboard

Feature suggestion: readOnlyArrays as configuration option

Open Q-Man opened this issue 6 years ago • 5 comments

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.

Q-Man avatar Feb 07 '18 15:02 Q-Man

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>;
}

vojtechhabarta avatar Feb 10 '18 14:02 vojtechhabarta

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.

Q-Man avatar Feb 12 '18 12:02 Q-Man

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).

vojtechhabarta avatar Feb 12 '18 14:02 vojtechhabarta

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.

Q-Man avatar Feb 12 '18 14:02 Q-Man

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.

danielwegener avatar Jun 24 '20 09:06 danielwegener