13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

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

[[415240]]

本文转载自微信公众号「三分钟学前端」,作者sisterAn 。转载本文请联系三分钟学前端公众号。

创新互联建站专注为客户提供全方位的互联网综合服务,包含不限于网站设计、成都网站建设、高邮网络推广、微信小程序开发、高邮网络营销、高邮企业策划、高邮品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联建站为所有大学生创业者提供高邮建站搭建服务,24小时服务热线:028-86922220,官方网址:www.cdcxhl.com

TypeScript 中 const 与 readonly 的区别?

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

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) 

区别

  
 
 
  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枚举)

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

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

区别

  
 
 
  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


网站标题:TypeScript中Const和Readonly的区别?枚举和常量枚举的区别?
当前链接:http://cdbrznjsb.com/article/dphdidp.html

其他资讯

让你的专属顾问为你服务