Typescript 的數據類型 除了javascript中常見的類型外還有幾個新面孔,下面讓我們來看看具體都有哪些?
- Tuple 允許表示一個已知元素數量和類型的數組,各元素的類型不必相同。
// Declare a tuple type
let x: [string, number];
x = ['hello', 10]; //Ok
// Initialize it incorrectly
x = [10, 'hello'] //Error
- 枚舉 enum 類型是javascript 標準類型的一個補充。
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
默認情況下,從0開始爲元素編號,但是可以手動指定成員的數值
enum Color {
Red = 1,
Green,
Blue
}
let c: Color = Color.Green
- Any 在編譯階段不清楚類型的變量可以指定該類型。
let notSure: any = 4;
notSure = "maybe a string insted";
notSure = false;
- Object 也可以移除編譯時的類型檢查,但在執行時不能調用它的任意方法,即使該方法存在
let notSure:any = 4;
notSure.ifItExists(); //Okay
let prettySure: Object = 4;
prettySure.toFixed(); // Error
寫在最後,類型斷言好比其他語言裏的類型轉換,但是不進行特殊的數據檢查和解構。
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).lenght