本文转载自微信公众号「三分钟学前端」,作者sisterAn 。转载本文请联系三分钟学前端公众号。
TypeScript 中不可变量的实现方法有两种:
使用 ES6 的 const 关键字声明的值类型
被 readonly 修饰的属性
TypeScript 中 readonly
TypeScript 中的只读修饰符,可以声明更加严谨的可读属性
通常在 interface 、 Class 、 type 以及 array 和 tuple 类型中使用它,也可以用来定义一个函数的参数
复制
// type type Foo = { readonly bar: number; }; // const 确保 'config' 不能够被改变了 const foo: Foo = { bar: 123 }; // 不能被改变 foo.bar = 456; // Error: foo.bar 为仅读属性
1.
2.
3.
4.
5.
6.
7.
8.
复制
// 函数 function foo(config: { readonly num: number }) { // .. } const config = { num: 123 } foo(config)
1.
2.
3.
4.
5.
6.
区别
const 用于变量, readonly 用于属性
const 在运行时检查, readonly 在编译时检查
const 声明的变量不得改变值,这意味着,const 一旦声明变量,就必须立即初始化,不能留到以后赋值; readonly 修饰的属性能确保自身不能修改属性,但是当你把这个属性交给其它并没有这种保证的使用者(允许出于类型兼容性的原因),他们能改变
复制
const foo: { readonly bar: number; } = { bar: 123 }; function iMutateFoo(foo: { bar: number }) { foo.bar = 456; } iMutateFoo(foo); console.log(foo.bar); // 456
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
此时,需要 iMutateFoo 明确的表示,他们的参数不可修改,那么编译器会发出错误警告:
复制
function iTakeFoo(foo: Foo) { foo.bar = 456; // Error: bar 属性只读 }
1.
2.
3.
const 保证的不是变量的值不得改动,而是变量指向的那个内存地址不得改动,例如使用 const 变量保存的数组,可以使用 push , pop 等方法。但是如果使用 ReadonlyArray 声明的数组不能使用 push , pop 等方法。
枚举和常量枚举(const枚举)
使用枚举可以清晰地表达意图或创建一组有区别的用例
复制
// 枚举 enum Color { Red, Green, Blue } // 常量枚举 const enum Color { Red, Green, Blue }
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
区别
枚举会被编译时会编译成一个对象,可以被当作对象使用
const 枚举会在 typescript 编译期间被删除,const 枚举成员在使用的地方会被内联进来,避免额外的性能开销
复制
// 枚举 enum Color { Red, Green, Blue } var sisterAn = Color.Red // 会被编译成 JavaScript 中的 var sisterAn = Color.Red // 即在运行执行时,它将会查找变量 Color 和 Color.Red
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
复制
// 常量枚举 const enum Color { Red, Green, Blue } var sisterAn = Color.Red // 会被编译成 JavaScript 中的 var sisterAn = 0 // 在运行时已经没有 Color 变量
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
来源:https://github.com/Advanced-Frontend/Daily-Interview-Question