sably
sably

Reputation: 177

how it's work `ReadonlyArray` property in typescript?

i have the snippet code:

let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
a[0] = 8;

console.log(ro); //expext to be [1,2,3,4] not ok
console.log(a);//expext to be [8,2,3,4] ok

when i change Array athe readonlyArray ro is changed? why?

Upvotes: 2

Views: 369

Answers (2)

SMAKSS
SMAKSS

Reputation: 10520

Since you're creating ro from a itself, both ro and a will have the same reference in memory, so whenever you change either of them, the other one will take effect of the other one.

How to create an array from each other without passing the reference?

  • You can use .slice()

    let a: number[] = [1, 2, 3, 4];
    let ro: ReadonlyArray<number> = a.slice();
    a[0] = 8;
    
    console.log(ro); //expext to be [1,2,3,4] ok
    console.log(a);//expext to be [8,2,3,4] ok
    
  • You can pass it by spread syntax.

    let a: number[] = [1, 2, 3, 4];
    let ro: ReadonlyArray<number> = [...a];
    a[0] = 8;
    
    console.log(ro); //expext to be [1,2,3,4] ok
    console.log(a);//expext to be [8,2,3,4] ok
    
  • You can use the Array.from() method, which makes a shallow copy of the existing array

    let a: number[] = [1, 2, 3, 4];
    let ro: ReadonlyArray<number> = Array.from(a);
    a[0] = 8;
    
    console.log(ro); //expext to be [1,2,3,4] ok
    console.log(a);//expext to be [8,2,3,4] ok
    

Upvotes: 3

User863
User863

Reputation: 20039

Create a copy using Array.from() or Spread operator

let a = [1, 2, 3, 4];
let ro = Array.from(a); // [...a]
a[0] = 8;

console.log(ro);
console.log(a);

For readonly, try using Object.freeze()

let a = [1, 2, 3, 4];
let ro = [...a];

Object.freeze(ro);

a[0] = 8;
ro[0] = 8;

console.log(a);
console.log(ro);

Upvotes: 1

Related Questions