microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
99.36k stars 12.31k forks source link

Multidimensional readonly arrays #30755

Open topaxi opened 5 years ago

topaxi commented 5 years ago

Search Terms

readonly array multi multidimensional

Suggestion

The readonly modifier should work with multidimensional arrays.

Use Cases

I assumed readonly number[][] to be multidimensional array which is readonly, but it translates to ReadonlyArray<number[]>, this feels like a footgun.

It is currently also not very intuitive which array is readonly: ReadonlyArray<number>[] or ReadonlyArray<number[]>, without trying it out.

Examples

I'd expect readonly number[][] to be equal to ReadonlyArray<ReadonlyArray<number>>

Explicitely "mixed mutable" arrays could be achieved using parens:

(readonly number[])[] == ReadonlyArray<number>[]
readonly (number[])[] == ReadonlyArray<number[]>

Checklist

My suggestion meets these guidelines:

Veetaha commented 5 years ago

@topaxi, as an alternative, you may use DeepReadonly<> type from 'ts-typedefs' package or use a non-jagged one-dimensional array, that will be more performant:

export class Matrix2D<T> {
    private matrix: T[];

    get(i: number, j: number) {
        return this.matrix[i * this.matrix.length + j];
    }
}

However, I agree that new syntax seems convoluted.

DeepReadonly<> Demo ![image](https://user-images.githubusercontent.com/36276403/55919765-d2a00000-5bff-11e9-9abb-d206fd20a7de.png)
waterplea commented 4 years ago

Ran into the same case. I've been working with old Angular for a while writing long ReadonlyArray<ReadonlyArray<T>> dreaming of the day I could update TS and use readonly modifier only to find it will not make things much shorter for me :(

MarsiBarsi commented 4 years ago

I agree with @waterplea. Now I have to use ReadonlyArray<ReadonlyArray<T>> or readonly ReadonlyArray<T>[]. The both options are not readable enough :(

jbrower2 commented 3 years ago

This isn't much more readable, but readonly (readonly number[])[] is a workaround (as seen in @Veetaha's image).