Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript 中 const 和 readonly 的区别?枚举和常量枚举的区别? #125

Open
sisterAn opened this issue Aug 3, 2021 · 0 comments

Comments

@sisterAn
Copy link
Owner

sisterAn commented Aug 3, 2021

TypeScript 中 const 与 readonly 的区别?

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 为仅读属性
// 函数
function foo(config: { readonly num: number }) {
  // ..
}
const config = { num: 123 }
foo(config)

区别

  1. const 用于变量, readonly 用于属性

  2. const 在运行时检查, readonly 在编译时检查

  3. 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

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

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

枚举和常量枚举的区别?

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

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

// 枚举
enum Color {
  Red,
  Green,
  Blue
}

// 常量枚举
const enum Color {
  Red,
  Green,
  Blue
}

区别

  1. 枚举会被编译时会编译成一个对象,可以被当作对象使用
  2. const 枚举会在 typescript 编译期间被删除,const 枚举成员在使用的地方会被内联进来,避免额外的性能开销
// 枚举
enum Color {
  Red,
  Green,
  Blue
}

var sisterAn = Color.Red
// 会被编译成 JavaScript 中的 var sisterAn = Color.Red
// 即在运行执行时,它将会查找变量 Color 和 Color.Red
// 常量枚举
const enum Color {
  Red,
  Green,
  Blue
}

var sisterAn = Color.Red
// 会被编译成 JavaScript 中的 var sisterAn = 0
// 在运行时已经没有 Color 变量
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant