最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Typescript?嚴(yán)格模式有多嚴(yán)格

 更新時間:2023年01月29日 14:40:44   作者:CUGGZ  
這篇文章主要為大家介紹了Typescript?嚴(yán)格模式有多嚴(yán)格實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

TypeScript 是微軟于 2012 年推出的一門語言,它是 JavaScript 的超集,具有更強(qiáng)的可選類型系統(tǒng)。TypeScript 和 JavaScript 一樣是有嚴(yán)格模式的,今天就來看看 TypeScript 中的嚴(yán)格模式如何開啟,以及它到底有多嚴(yán)格!

TypeScript 的配置項都寫在項目根目錄名為 tsconfig.json 的配置文件中,可以通過以下方式來開啟嚴(yán)格模式:

{
  ...
  "compilerOptions": {
    "strict": true,
    ...
  },
  ...
}

TypeScript 編譯器有超過 90 個不同的配置項。其中 7 個是關(guān)于嚴(yán)格模式的:

  • noImplicitAny
  • noImplicitThis
  • alwaysStrict
  • strictBindCallApply
  • strictNullChecks
  • strictPropertyInitialization
  • strictFunctionTypes

當(dāng)在 tsconfig.json 中開啟嚴(yán)格模式之后,就相當(dāng)于開啟了這些配置:

{
  ...
  "compilerOptions": {
    "noImplicitAny": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "strictBindCallApply": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    ...
  }
  ...
}

下面就來分別看一下這些選項都有什么含義。

noImplicitAny

此規(guī)則不允許變量或函數(shù)參數(shù)具有隱式 any 類型。來看下面的例子:

const add10 = number => number + 10;

當(dāng)啟用了嚴(yán)格模式時,函數(shù)參數(shù) number 就報錯了:

參數(shù)“number”隱式具有“any”類型。ts(7006)

要想修復(fù)這個報錯,只需給參數(shù)或變量顯式指定類型:

const add10 = (number: number) => number + 10;

因此 noImplicitAny 規(guī)則可以確保代碼更具可讀性。否則,add10 函數(shù)的調(diào)用者需要推斷參數(shù)是一個數(shù)字,那使用 TypeScript 還有什么意義呢?

noImplicitThis

此規(guī)則不允許 this 隱式定義上下文。來看下面的例子:

class Person {
  weight: number;
  height: number; 
  constructor(weight: number, height: number) {
    this.weight = weight;
    this.height = height;
  } 
  getBodyMassIndex() {
    return function () {
      return this.weight / (this.height * this.height);
    };
  }
}

當(dāng)啟用了嚴(yán)格模式時,getBodyMassIndex 中的 this 就報錯了:

"this" 隱式具有類型 "any",因?yàn)樗鼪]有類型注釋。ts(2683)

解決這個問題的方法就是使用箭頭函數(shù),因?yàn)榧^函數(shù)使用其父級的執(zhí)行上下文:

class Person {
  weight: number;
  height: number; 
  constructor(weight: number, height: number) {
    this.weight = weight;
    this.height = height;
  } 
  getBodyMassIndex() {
    return () => {
      return this.weight / (this.height * this.height);
    };
  }
}

alwaysStrict

此規(guī)則指定始終以嚴(yán)格模式檢查每個模塊,并且在編譯之后的 JavaScript 文件中加入"use strict",用來告訴瀏覽器該 JavaScript 為嚴(yán)格模式。

ECMAScript 嚴(yán)格模式是在 ES5 中引入的,它只是向編譯器提示代碼應(yīng)該以嚴(yán)格模式執(zhí)行,使用嚴(yán)格模式可以使代碼更以更安全、高效的方式運(yùn)行。

strictBindCallApply

此規(guī)則可以確保使用具有正確參數(shù)的 call()、bind()apply() 函數(shù)。來看下面的例子:

const logNumber = (x: number) => {
  console.log(`number:${x}`)
}
logNumber.call(undefined, "10"); // 

當(dāng)啟用了嚴(yán)格模式時,getBodyMassIndex 中的 this 就報錯了:

類型“string”的參數(shù)不能賦給類型“number”的參數(shù)。ts(2345)

當(dāng)遇到這種報錯時,只需檢查函數(shù)調(diào)用的參數(shù),并使用正常的方式調(diào)用:

logNumber.call(undefined, 10); // number:10

strictNullChecks

此規(guī)則使得 null和 undefined 值不能賦值給非這兩種類型的值,別的類型的值也不能賦給它們。除了 any 類型,還有個例外就是 undefined 可以賦值給 void 類型。這個選項可以幫助 Uncaught TypeError 錯誤。來看下面的例子:

interface Book {
    name: string;
    author: string;
  }
const books: Book[] = [ {name: 'Test1', author: 'Max'} ];
const getBookByAuthor = (author: string) => books.find((book) => book.author = author);
const book = getBookByAuthor("John");
console.log(book.name);

當(dāng)啟用了嚴(yán)格模式時,打印 book.name 時就報錯了:

對象可能為“未定義”。ts(2532)

如果未開啟嚴(yán)格模式,即使 book.name 可能未定義,此代碼也會編譯。想要修復(fù)這個問題,就需要為要編譯的代碼添加 null 檢查:

interface Book {
  name: string;
  author: string;
}
const books: Book[] = [ {name: 'Test1', author: 'Max'} ];
const getBookByAuthor = (author: string) => books.find((book) => book.author = author);
const book = getBookByAuthor("John");
if (book) {
  console.log(book.name);
} else {
  console.log('Book not found');
}

函數(shù)中也是一樣的,來看下面的例子:

interface Book {
    name: string;
    author: string;
  }
const books: Book[] = [ {name: 'Test1', author: 'Max'} ];
const getBookByAuthor = (author: string) => books.find((book) => book.author = author);
const book = getBookByAuthor("John");
const logBookName = (book: Book) => {
    console.log(book.name);
}
logBookName(book); 

如果啟用了嚴(yán)格模式時,調(diào)用 logBookName(book); 時就會報錯:

類型“Book | undefined”的參數(shù)不能賦給類型“Book”的參數(shù)。
  不能將類型“undefined”分配給類型“Book”。ts(2345)

這里提供兩種解決方案:

  • A:將logBookName 函數(shù)參數(shù)類型設(shè)置為 Book | undefined
  • Bnull 檢查條件調(diào)用
// A
const logBookName = (book: Book | undefined) => {
    if (book) {
        console.log(book.name);
    }
    else {
        console.log('not book');
    }
}
// B
if (book) {
    logBookName(book);
}

使用該規(guī)則時,可以強(qiáng)制開發(fā)人員編寫具有更好類型描述的代碼。

strictPropertyInitialization

此規(guī)則將強(qiáng)制在構(gòu)造函數(shù)中初始化所有屬性值。來看下面的例子:

class User {
    name: string;
    age: number;
    occupation: string | undefined;   
    constructor(name: string) {
        this.name = name;
    }
}

在上面的代碼塊中有一個 User 類,constructor() 方法是初始化其實(shí)例屬性的地方。當(dāng)實(shí)例化一個類對象時,JavaScript 會自動調(diào)用 constructor() 方法。Typescript 要求要么初始化定義的屬性,要么指定一個 undefined 類型。因此,當(dāng)編譯上面的代碼時,將會提示以下錯誤:

屬性“age”沒有初始化表達(dá)式,且未在構(gòu)造函數(shù)中明確賦值。ts(2564)

對于上面的代碼,可以這樣改:

// A:指定 undefined 類型
class User {
    name: string;
    age: number | undefined;
    occupation: string | undefined;
    constructor(name: string) {
        this.name = name;
    }
}
// B:初始化定義的屬性
class User {
    name: string;
    age: number;
    occupation: string | undefined;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

strictFunctionTypes

此規(guī)則會更徹底地檢查函數(shù)參數(shù)。Typescript 參數(shù)默認(rèn)是雙向協(xié)變的,這意味著它們既可以是協(xié)變的,也可以是逆變的。方差是一種深入了解子類型關(guān)系的方法。當(dāng)參數(shù)是協(xié)方差時,我們可以將特定類型分配給更廣泛的類型(例如將子類型分配給超類型)。逆變是相反的:可以將更廣泛的類型分配給特定類型(例如將超類型分配給子類型)。

// 非嚴(yán)格模式
interface Animal {
  name: string;
}
interface Dog extends Animal {
  breeds: Array<string>;
}
let getDogName = (dog: Dog) => dog.name;
let getAnimalName = (animal: Animal) => animal.name;
getDogName = getAnimalName;  // Ok
getAnimalName = getDogName;  // Ok

上面的代碼運(yùn)行時并沒有提示錯誤,默認(rèn)情況下參數(shù)是雙向協(xié)變比較的。超類型 getAnimalName 和子類型 getDogName 的方法可以相互分配。當(dāng)開啟嚴(yán)格模式之后,則 TypeScript 的參數(shù)進(jìn)行逆變比較。

// 嚴(yán)格模式
interface Animal {
  name: string;
}
interface Dog extends Animal {
  breeds: Array<string>;
}
let getDogName = (dog: Dog) => dog.name;
let getAnimalName = (animal: Animal) => animal.name;
getDogName = getAnimalName; // Ok
getAnimalName = getDogName; // Error

當(dāng)開啟嚴(yán)格模式時,最后一行將報以下錯誤:

不能將類型“(dog: Dog) => string”分配給類型“(animal: Animal) => string”。
  參數(shù)“dog”和“animal” 的類型不兼容。
    類型 "Animal" 中缺少屬性 "breeds",但類型 "Dog" 中需要該屬性。ts(2322)

這里,getAnimalName 是比 getDogName 更廣泛的函數(shù)。因此,在這種情況下,無法將超類型分配給子類型。但是,可以將子類型分配給超類型。大多數(shù)時候,函數(shù)參數(shù)應(yīng)該是逆變的,而不是雙向協(xié)變的。如果開啟嚴(yán)格模式,Typescript 將不會將函數(shù)參數(shù)視為雙向協(xié)變。

以上就是詳解Typescript 嚴(yán)格模式有多嚴(yán)格的詳細(xì)內(nèi)容,更多關(guān)于Typescript 嚴(yán)格模式的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • typescript封裝消息提示框插件ew-message使用實(shí)戰(zhàn)

    typescript封裝消息提示框插件ew-message使用實(shí)戰(zhàn)

    這篇文章主要為大家介紹了typescript封裝消息提示框插件ew-message使用實(shí)戰(zhàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11
  • require.js使用方法的簡單代碼講解筆記

    require.js使用方法的簡單代碼講解筆記

    頁面需要加載多個js文件時,加載時瀏覽器會停止網(wǎng)頁渲染,加載文件越多,網(wǎng)頁失去響應(yīng)的時間就會越長;由于js文件之間存在依賴關(guān)系,必須嚴(yán)格保證加載順序,當(dāng)依賴關(guān)系很復(fù)雜的時候,代碼的編寫和維護(hù)都會變得困難。這種情況下require.js插件應(yīng)運(yùn)而生。
    2022-12-12
  • layui中的layer彈出層自定義樣式更改背景

    layui中的layer彈出層自定義樣式更改背景

    layui中的layer彈出層有很多提示框,但是我們使用最多的應(yīng)該就幾種,layer.msg、layer.alert、layer.open、layer.load等。layer?有內(nèi)置的skin:layui-layer-lan,layui-layer-molv,可以直接使用。skin不僅允許你傳入layer內(nèi)置的樣式class名,可以自定義class名。
    2023-06-06
  • Typescript使用裝飾器實(shí)現(xiàn)接口字段映射與Mock實(shí)例

    Typescript使用裝飾器實(shí)現(xiàn)接口字段映射與Mock實(shí)例

    這篇文章主要為大家介紹了Typescript使用裝飾器實(shí)現(xiàn)接口字段映射與Mock實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-04-04
  • TypeScript快速上手—html中使用ts的兩種方法

    TypeScript快速上手—html中使用ts的兩種方法

    TypeScript使用命令行編譯器tsc或其他工具手動執(zhí)行編譯,在html使用s時編譯為JavaScript,那么有沒有辦法簡化過程,不編譯直接使用,本文介紹html中使用TypeScript的兩種方法
    2024-07-07
  • TypeScript 基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)哈希表 HashTable教程

    TypeScript 基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)哈希表 HashTable教程

    這篇文章主要為大家介紹了TypeScript 基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)哈希表 HashTable教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-02-02
  • Underscore.js常用方法總結(jié)

    Underscore.js常用方法總結(jié)

    這篇文章主要介紹了Underscore.js常用方法總結(jié),本文講解了Underscore.js概述、在node.js下安裝、與集合有關(guān)的方法、與對象有關(guān)的方法、與函數(shù)相關(guān)的方法等內(nèi)容,需要的朋友可以參考下
    2015-02-02
  • less簡單入門(CSS 預(yù)處理語言)

    less簡單入門(CSS 預(yù)處理語言)

    Less 是一門 CSS 預(yù)處理語言,它擴(kuò)充了 CSS 語言,增加了諸如變量、混合(mixin)、函數(shù)等功能,讓 CSS 更易維護(hù)、方便制作主題、擴(kuò)充
    2017-03-03
  • TypeScript中的遞歸類型示例解析

    TypeScript中的遞歸類型示例解析

    這篇文章主要為大家介紹了TypeScript中的遞歸類型示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-04-04
  • rollup?cli開發(fā)全面系統(tǒng)性rollup源碼分析

    rollup?cli開發(fā)全面系統(tǒng)性rollup源碼分析

    這篇文章主要為大家介紹了rollup?cli開發(fā)全網(wǎng)系統(tǒng)性rollup源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-01-01

最新評論

大同县| 壶关县| 农安县| 琼海市| 怀远县| 无锡市| 沁阳市| 舒兰市| 黎城县| 申扎县| 元谋县| 湾仔区| 潮安县| 新民市| 诏安县| 凉城县| 山东省| 四平市| 南康市| 崇阳县| 若羌县| 包头市| 吉安县| 台东市| 佛教| 塔城市| 高雄县| 中牟县| 宁明县| 炎陵县| 宜城市| 常熟市| 周口市| 兴安盟| 固阳县| 竹山县| 黔西县| 乐安县| 那曲县| 托克托县| 会同县|