TypeScript初览(一)

基础类型(一)

boolean编程

let isDone: boolean = false;

number数组

支持2、8、10、十六进制
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;

stringcode

可使用双引号或单引号表示字符串
let name:string = "bob";
name = "smith";

也可使用模板字符串,定义多行文本和内嵌表达式,这种字符串是被反引号包围,而且以${ expr }这种形式嵌入表达式
let name:string = `Gene`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ name }.
I'll be ${ age + 1 } years old next month.`;
这与下面定义sentence的方式相同:
let sentence: string = "Hello, my name is" + name + ".\n\n" + 
"I'll be" + (age + 1) + "years old next month.";

Array索引

有两种方式能够定义数组。第一种,能够在元素类型后面接上[],表示由此类型元素组成的一个数组:
let list: number[] = [1, 2, 3];
第二种方式是使用数组泛型,Array<元素类型>:
let list: Array<number> = [1, 2, 3];

Tupleip

元组类型容许表示一个已知元素数量和类型的数组,各元素的类型没必要相同。好比,你能够定义一对值分别为 string 和 number 类型的元组。
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error 

当访问一个已知索引的元素,会获得正确的类型:
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

当访问一个越界的元素,会使用联合类型替代:
x[3] = 'world'; // OK,字符串能够赋值给(string | number)类型
console.log(x[5].toString()); // OK, 'string' 和 'number' 都有 toString
x[6] = true; // Error, 布尔不是(string | number)类型

enum字符串

enum类型是对JavaScript标准数据类型的一个补充。使用枚举类型能够为一组数值赋予友好的名字。
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
默认状况下,从0开始为元素编号。你也能够手动的指定成员的数值。例如,将上面的例子改为从1开始编号:
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;
或者所有都采用手动赋值:
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;

枚举类型提供的一个便利是你能够由枚举的值获得它的名字。例如,咱们知道数值为2,可是不肯定它映射到Color里的哪一个名字,咱们能够查找相应的名字:
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
alert(colorName);

Anystring

有时候,咱们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。这些值可能来自于动态的内容,好比来自用户输入或第三方代码库。这种状况下,咱们不但愿类型检查器对这些值进行检查而是直接让它们经过编译阶段的检查。那么可使用any类型来标记这些变量:
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

在对现有代码进行改写的时候,any类型是十分有用的,它容许你在编译时可选择地包含或移除类型检查。你可能认为Object有类似的做用,就像在其余语言中那样。可是Object类型的变量只是容许你给它赋任意值 - 可是却不可以在它上面调用任意的方法,即便它真的有这些方法:
let notSure: any = 4;
notSure.ifItExists(); // Okay, ifItExists might exist at runtime
notSure.toFixed(); // Okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

当你只知道一部分数据的类型时, any类型也是有用的。好比, 你有一个数组,它包含了不一样的类型的数据:
let list: any[] = [1, true, "free"];
list[1] = 100;
相关文章
相关标签/搜索