在使用 Angular 作項目的時候,對 TypeScript 的類型判斷不太熟練,爲了方便查找,特地對 TypeScript 的類型判斷作了簡單梳理。文章只是 TS 官網的內容摘要,沒有高深的知識,想要深刻學習 TS 還要看官網文檔。數組
// 布爾值 let isDone: boolean = false; // 數字 let decLiteral: number = 6; let hexLiteral: number = 0xf00d; let binaryLiteral: number = 0b1010; let octalLiteral: number = 0o744; // 字符串 let name: string = "bob"; name = "smith"; // 數組 let list: number[] = [1, 2, 3]; // 數組泛型 let list: Array<number> = [1, 2, 3]; //元組 Tuple let x: [string, number]; x = ['hello', 10]; // OK x = [10, 'hello']; // Error // 枚舉 enum Color {Red, Green, Blue} let c: Color = Color.Green; // Any let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean // Void function warnUser(): void { alert("This is my warning message"); } // Null 和 Undefined let u: undefined = undefined; let n: null = null; // Never function error(message: string): never { throw new Error(message); } function fail() { return error("Something failed"); } function infiniteLoop(): never { while (true) { } }
類型斷言比如其它語言裏的類型轉換,可是不進行特殊的數據檢查和解構。 它沒有運行時的影響,只是在編譯階段起做用。ide
let someValue: any = "this is a string"; // 「尖括號」語法 let strLength: number = (<string>someValue).length; // as語法 let strLength: number = (someValue as string).length;
TypeScript 的核心原則之一是對值所具備的結構進行類型檢查。 它有時被稱作「鴨式辨型法」或「結構性子類型化」。 在 TypeScript 裏,接口的做用就是爲這些類型命名和爲你的代碼或第三方代碼定義契約。函數
interface LabelledValue { label: string; } // 可選屬性 interface SquareConfig { color?: string; width?: number; } // 只讀屬性 interface Point { readonly x: number; readonly y: number; } // 函數類型 interface SearchFunc { (source: string, subString: string): boolean; } // 可索引的類型 interface StringArray { [index: number]: string; } // 類類型 interface ClockInterface { currentTime: Date; }
咱們把這個版本的 identity
函數叫作泛型,由於它能夠適用於多個類型。 不一樣於使用 any
,它不會丟失信息,像第一個例子那像保持準確性,傳入數值類型並返回數值類型。oop
function identity<T>(arg: T): T { return arg; }