ts中特殊符號


最全特殊符號鏈接:https://blog.csdn.net/qiwoo_weekly/article/details/108557466

 

1.后綴表達式操作符 ! 可以用於斷言操作對象是非 null 和非 undefined 類型: 

function x (y:string | undefined | null) {

const a:string = y;   // error

const b:string = y!;  // ok

}

2.可選鏈?. 編寫代碼時如果遇到 null 或 undefined 就可以立即停止某些表達式的運行

obj?.prop

obj?.[expr]

 arr?.[index]

 func?.(args)

這里我們來舉一個可選的屬性訪問的例子:

const val = a?.b;

為了更好的理解可選鏈,我們來看一下該 const val = a?.b 語句編譯生成的 ES5 代碼:

var val = a === null || a === void 0 ? void 0 : a.b;

可選鏈函數調用:let result = obj.customMethod?.();

3.??.空值合並運算符:當左側操作數為 null 或 undefined 時,其返回右側的操作數,否則返回左側的操作數。

eg: 

const foo = null ?? 'default string'; 

console.log(foo); // 輸出:"default string"

4.?:可選屬性:TypeScript 中的接口是一個非常靈活的概念,除了可用於對類的一部分行為進行抽象以外,也常用於對「對象的形狀(Shape)」進行描述。

interface Person { 

  name: string; 

 age?: number; 

}  

let lolo: Person  = {

  name: "lolo"  

}

5.& 運算符:可以將現有的多種類型疊加到一起成為一種類型,它包含了所需的所有類型的特性。

type PartialPointX = { x: number; };

type Point = PartialPointX & { y: number; };

let point: Point = {

 x: 1,

 y: 1

}

6.| 分隔符:在 TypeScript 中聯合類型(Union Types)表示取值可以為多種類型中的一種,聯合類型使用 | 分隔每個類型。聯合類型通常與 null 或 undefined 一起使用:

const sayHello = (name: string | undefined) => { /* ... */ };


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM