TypeScript 中 Const 和 Readonly 的區(qū)別?枚舉和常量枚舉的區(qū)別?
本文轉(zhuǎn)載自微信公眾號「三分鐘學(xué)前端」,作者sisterAn 。轉(zhuǎn)載本文請聯(lián)系三分鐘學(xué)前端公眾號。
TypeScript 中 const 與 readonly 的區(qū)別?
TypeScript 中不可變量的實現(xiàn)方法有兩種:
- 使用 ES6 的 const 關(guān)鍵字聲明的值類型
- 被 readonly 修飾的屬性
TypeScript 中 readonly
TypeScript 中的只讀修飾符,可以聲明更加嚴(yán)謹(jǐn)?shù)目勺x屬性
通常在 interface 、 Class 、 type 以及 array 和 tuple 類型中使用它,也可以用來定義一個函數(shù)的參數(shù)
- // type
- type Foo = {
- readonly bar: number;
- };
- // const 確保 'config' 不能夠被改變了
- const foo: Foo = { bar: 123 };
- // 不能被改變
- foo.bar = 456; // Error: foo.bar 為僅讀屬性
- // 函數(shù)
- function foo(config: { readonly num: number }) {
- // ..
- }
- const config = { num: 123 }
- foo(config)
區(qū)別
- const 用于變量, readonly 用于屬性
- const 在運(yùn)行時檢查, readonly 在編譯時檢查
- const 聲明的變量不得改變值,這意味著,const 一旦聲明變量,就必須立即初始化,不能留到以后賦值; readonly 修飾的屬性能確保自身不能修改屬性,但是當(dāng)你把這個屬性交給其它并沒有這種保證的使用者(允許出于類型兼容性的原因),他們能改變
- const foo: {
- readonly bar: number;
- } = {
- bar: 123
- };
- function iMutateFoo(foo: { bar: number }) {
- foo.bar = 456;
- }
- iMutateFoo(foo);
- console.log(foo.bar); // 456
此時,需要 iMutateFoo 明確的表示,他們的參數(shù)不可修改,那么編譯器會發(fā)出錯誤警告:
- function iTakeFoo(foo: Foo) {
- foo.bar = 456; // Error: bar 屬性只讀
- }
- const 保證的不是變量的值不得改動,而是變量指向的那個內(nèi)存地址不得改動,例如使用 const 變量保存的數(shù)組,可以使用 push , pop 等方法。但是如果使用 ReadonlyArray
聲明的數(shù)組不能使用 push , pop 等方法。
枚舉和常量枚舉的區(qū)別?
枚舉和常量枚舉(const枚舉)
使用枚舉可以清晰地表達(dá)意圖或創(chuàng)建一組有區(qū)別的用例
- // 枚舉
- enum Color {
- Red,
- Green,
- Blue
- }
- // 常量枚舉
- const enum Color {
- Red,
- Green,
- Blue
- }
區(qū)別
- 枚舉會被編譯時會編譯成一個對象,可以被當(dāng)作對象使用
- const 枚舉會在 typescript 編譯期間被刪除,const 枚舉成員在使用的地方會被內(nèi)聯(lián)進(jìn)來,避免額外的性能開銷
- // 枚舉
- enum Color {
- Red,
- Green,
- Blue
- }
- var sisterAn = Color.Red
- // 會被編譯成 JavaScript 中的 var sisterAn = Color.Red
- // 即在運(yùn)行執(zhí)行時,它將會查找變量 Color 和 Color.Red
- // 常量枚舉
- const enum Color {
- Red,
- Green,
- Blue
- }
- var sisterAn = Color.Red
- // 會被編譯成 JavaScript 中的 var sisterAn = 0
- // 在運(yùn)行時已經(jīng)沒有 Color 變量
來源:https://github.com/Advanced-Frontend/Daily-Interview-Question