Typescript 基本数据类型
一、基本数据类型
- Boolean
- Number
- String
- Array
- Tuple
- Enum
- Any
- Void
- Null 和 Undefined
- Never
二、代码示例
//布尔值
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 name: string = `Gene`;
let age: number = 37;
let sentence: string = `Hello, my name is ${name}.
I'll be ${age + 1} years old next month.`;
//数组
let list: number[] = [1, 2, 3];
//Array<元素类型>
let list: Array<number> = [1, 2, 3];
//元组 Tuple
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
//枚举
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green,
Blue
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green = 2,
Blue = 4
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green,
Blue
}
let colorName: string = Color[2];
alert(colorName); // 显示'Green'因为上面代码里它的值是2
//Any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
//Any数组
let list: any[] = [1, true, "free"];
list[1] = 100;
//Void
function warnUser(): void {
alert("This is my warning message");
}
let unusable: void = undefined;
//Null 和 Undefined
let u: undefined = undefined;
let n: null = null;
//Never
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message);
}
// 推断的返回值类型为never
function fail() {
return error("Something failed");
}
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {}
}
//类型断言
let someValue1: any = "this is a string";
let strLength1: number = (someValue1 as string).length;
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;