打字稿中const和readonly的区别 [英] Difference between const and readonly in typescript

查看:36
本文介绍了打字稿中const和readonly的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打字稿中的常量与只读

将变量声明为 readonly 将不允许我们覆盖,即使它们是公共属性.

const 的行为,

const SOME_VARIABLE:number = 10;

如果我覆盖它的值,它将如何工作?

解决方案

const 变量不能重新赋值,就像一个 readonly 属性一样.

本质上,当您定义一个属性时,您可以使用 readonly 来防止重新分配.这实际上只是一个编译时检查.

当您定义 const 变量(并定位到更新版本的 JavaScript 以在输出中保留 const)时,也会在运行时进行检查.

所以它们实际上都做同样的事情,但一个用于变量,另一个用于属性.

const x = 5;//不允许x = 7;类示例{公共只读 y = 6;}var e = new Example();//不允许e.y = 4;

重要说明...无法重新分配"与不变性不同.

const myArr = [1, 2, 3];//不允许myArr = [4, 5, 6]//完全没问题myArr.push(4);//完全没问题myArr[0] = 9;

Constant vs readonly in typescript

Declaring a variable as readonly will not allow us to override even if they are public properties.

How const behaves,

const SOME_VARIABLE:number = 10;

If I override its value, how will it work?

解决方案

A const variable cannot be re-assigned, just like a readonly property.

Essentially, when you define a property, you can use readonly to prevent re-assignment. This is actually only a compile-time check.

When you define a const variable (and target a more recent version of JavaScript to preserve const in the output), the check is also made at runtime.

So they effectively both do the same thing, but one is for variables and the other is for properties.

const x = 5;

// Not allowed
x = 7;


class Example {
    public readonly y = 6;
}

var e = new Example();

// Not allowed
e.y = 4;

Important note... "cannot be re-assigned" is not the same as immutability.

const myArr = [1, 2, 3];

// Not allowed
myArr = [4, 5, 6]

// Perfectly fine
myArr.push(4);

// Perfectly fine
myArr[0] = 9;

这篇关于打字稿中const和readonly的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆