欢迎来到3672js教程,我们关注js教程、js框架、js代码特效等。

TypeScript 中 Const 和 Readonly 的区别?枚举和常量枚举的区别?,

3672Js.Com2021-08-04 12:01 来源:未知 阅读:3101 关注度2

TypeScript 中 Const 和 Readonly 的区别?枚举和常量枚举的区别?,


TypeScript 中 const 与 readonly 的区别?

TypeScript 中不可变量的实现方法有两种:

  • 使用 ES6 的 const 关键字声明的值类型
  • 被 readonly 修饰的属性

TypeScript 中 readonly

TypeScript 中的只读修饰符,可以声明更加严谨的可读属性

通常在 interface 、 Class 、 type 以及 array 和 tuple 类型中使用它,也可以用来定义一个函数的参数

  1. // type 
  2. type Foo = { 
  3.   readonly bar: number; 
  4. }; 
  5. // const 确保 'config' 不能够被改变了 
  6. const foo: Foo = { bar: 123 }; 
  7. // 不能被改变 
  8. foo.bar = 456; // Error: foo.bar 为仅读属性 
  1. // 函数 
  2. function foo(config: { readonly num: number }) { 
  3.   // .. 
  4. const config = { num: 123 } 
  5. foo(config) 

区别

  • const 用于变量, readonly 用于属性
  • const 在运行时检查, readonly 在编译时检查
  • const 声明的变量不得改变值,这意味着,const 一旦声明变量,就必须立即初始化,不能留到以后赋值; readonly 修饰的属性能确保自身不能修改属性,但是当你把这个属性交给其它并没有这种保证的使用者(允许出于类型兼容性的原因),他们能改变
  1. const foo: { 
  2.   readonly bar: number; 
  3. } = { 
  4.   bar: 123 
  5. }; 
  6.  
  7. function iMutateFoo(foo: { bar: number }) { 
  8.   foo.bar = 456; 
  9.  
  10. iMutateFoo(foo); 
  11. console.log(foo.bar); // 456 

此时,需要 iMutateFoo 明确的表示,他们的参数不可修改,那么编译器会发出错误警告:

  1. function iTakeFoo(foo: Foo) { 
  2.   foo.bar = 456; // Error: bar 属性只读 
  • const 保证的不是变量的值不得改动,而是变量指向的那个内存地址不得改动,例如使用 const 变量保存的数组,可以使用 push , pop 等方法。但是如果使用 ReadonlyArray 声明的数组不能使用 push , pop 等方法。

枚举和常量枚举的区别?

枚举和常量枚举(const枚举)

使用枚举可以清晰地表达意图或创建一组有区别的用例

  1. // 枚举 
  2. enum Color { 
  3.   Red, 
  4.   Green, 
  5.   Blue 
  6.  
  7. // 常量枚举 
  8. const enum Color { 
  9.   Red, 
  10.   Green, 
  11.   Blue 

区别

  • 枚举会被编译时会编译成一个对象,可以被当作对象使用
  • const 枚举会在 typescript 编译期间被删除,const 枚举成员在使用的地方会被内联进来,避免额外的性能开销
  1. // 枚举 
  2. enum Color { 
  3.   Red, 
  4.   Green, 
  5.   Blue 
  6.  
  7. var sisterAn = Color.Red 
  8. // 会被编译成 JavaScript 中的 var sisterAn = Color.Red 
  9. // 即在运行执行时,它将会查找变量 Color 和 Color.Red 

  1. // 常量枚举 
  2. const enum Color { 
  3.   Red, 
  4.   Green, 
  5.   Blue 
  6.  
  7. var sisterAn = Color.Red 
  8. // 会被编译成 JavaScript 中的 var sisterAn = 0 
  9. // 在运行时已经没有 Color 变量 

来源:https://github.com/Advanced-Frontend/Daily-Interview-Question

鸿蒙官方战略合作共建——HarmonyOS技术社区

本站文章为3672js教程网友分享投稿,版权归原作者,欢迎任何形式的转载,但请务必注明出处。同时文章内容如有侵犯了您的权益,请联系我们处理。
评论已被关闭
{dede:include filename="foot.htm"/}