TypeScript中的只读属性

学习博客的笔记,博客链接:Read-Only Properties in TypeScript — Marius Schulz
TS系列:TypeScript Evolution — Marius Schulz

标记为readonly的属性只能在初始化期间或从同一类的构造函数中赋值。所有其他分配都是不允许的。

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.

举个例子,定义一个Point类型,它的属性x和y都是readonly的:

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

它在初始化时赋值:

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

之后再想修改就会报错:

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

只读type

想要移动x,但因为readonly不能修改入参。代码如下会报错:

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

我们可以用这种方式:

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

只读class

class Circle {
    
    
	readonly radius: number;

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

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

被标记为readonly,不能写入,只能在构造函数处初始化。
可以读取,没标记private默认为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;

只读索引

定义一个接口,它的索引是只读的:

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

由于索引是只读的,不能使用索引对数组赋值

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;

readonly修饰符是TypeScript的类型系统的一部分。编译器只使用它来检查非法的属性赋值。一旦TypeScript代码被编译成JavaScript,readonly的所有概念都消失了。

猜你喜欢

转载自blog.csdn.net/karshey/article/details/134268109