Read-only properties in TypeScript

Notes from learning blog, blog link:Read-Only Properties in TypeScript — Marius Schulz
TS series:TypeScript Evolution — Marius Schulz

Properties marked readonly can only be assigned during initialization or from a constructor of the same class. All other allocations are not allowed.

Properties marked with readonly can only be assigned to during initialization or from within a constructor of the same class. All other assignments are disallowed.

For example, define a Point type whose attributes x and y are bothreadonly:

type Point = {
    
    
  readonly x: number;
  readonly y: number;
};

It is assigned a value on initialization:

const origin: Point = {
    
     x: 0, y: 0 };

If you try to modify it later, you will get an error:

// Error: Left-hand side of assignment expression
// cannot be a constant or read-only property
origin.x = 100;

read-only type

wants to move x, but the input parameters cannot be modified because readonly. The following code will report an error:

function moveX(p: Point, offset: number): Point {
    
    
	p.x += offset;
	return p;
}

We can do it this way:

function moveX(p: Point, offset: number): Point {
    
    
	return {
    
    
		x: p.x + offset,
		y: p.y,
	};
}

read-only class

class Circle {
    
    
	readonly radius: number;

	constructor(radius: number) {
    
    
		this.radius = radius;
	}

	get area() {
    
    
		return Math.PI * this.radius ** 2;
	}
}

is marked as readonly, cannot be written, and can only be initialized in the constructor.
can be read, no mark privatedefaults to public.

const unitCircle = new Circle(1);
unitCircle.radius; // 1
unitCircle.area; // 3.141592653589793

// Error: Left-hand side of assignment expression
// cannot be a constant or read-only property
unitCircle.radius = 42;

// Error: Left-hand side of assignment expression
// cannot be a constant or read-only property
unitCircle.area = 42;

read-only index

Define an interface whose index is read-only:

interface ReadonlyArray<T> {
    
    
  readonly length: number;
  // ...
  readonly [n: number]: T;
   // 索引n的类型是number,设为readonly,数组对应取到的值是泛型T
}

Since indexes are read-only, you cannot use indexes to assign values ​​to arrays.

const primesBelow10: ReadonlyArray<number> = [2, 3, 5, 7];

// 报错
// Error: Left-hand side of assignment expression
// cannot be a constant or read-only property
primesBelow10[4] = 11;

The readonly modifier is part of TypeScript's type system. The compiler only uses it to check for illegal property assignments. Once TypeScript code is compiled into JavaScript, all notions of readonly disappear.

Guess you like

Origin blog.csdn.net/karshey/article/details/134268109