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