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的所有概念都消失了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值