02-基本数据类型
1.boolean 布尔类型
let isDone:boolean = false|true;
2.number 数字类型
ts数字都是浮点数,数字可以使用es2015的二进制、八进制、十六进制
let decLiteral:number = 6;
3.string 字符串类型
可以使用单引、双引、模板字符串
let name:string = "bob"; let job:string = 'engineer'
let animal:string = '喵';
let like:string = `吃${animal}肉`;
4.数组 类型
声明方式一
let animal:string[] = [ '狗', '猫', '大象' ]; console.log(animal)
声明方式二
let list:Array<number> = [1,2,3];
5.元祖(Tuple)
1.元祖可以在数组中声明多种类型的值
2.越界赋值会使用联合类型(string | number)
let x:[string,number] = ['hello',10];
console.log(x[0].substring(0,1));
x[3] = '你好'; // ok
x[4] = true; // Type 'true' is not assignable to type 'string | number'
6.枚举(enum)
enum Color {Red, Green, Blue}
let c: Color = Color.Green; // 默认从0开始赋值
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green; // 也可以使用手动赋值
console.log(Color[2]) //也可以通过枚举的值获取它的名字
7.Any 任意类型
有时我们不确定变量是什么类型的时候,我们使用any
let notSure:any = 4; notSure = '1 giao wo di giao giao'; console.log(notSure);
let list:any[] = [true,'你好',1919] //true
8.void 空类型
function warnUser(): void { console.log("This is my warning message"); } warnUser() let unusable: void = undefined //void声明变量可以赋值undefined null
9.null与undefined
null与undefined是其他类型的子集
let n:null = null;
let n1:number = undefined;
let u:undefined = undefined;
console.log(n); //null
console.log(n1); //undefined
console.log(u); //undefined
10.never 永不存在的值的类型
function error(message: string): never { throw new Error(message); } function fail():never { return error("Something failed"); } console.log(fail());
11.Object
declare function create(o: object | null): void; create({ prop: 0 }); // OK create(null); // OK
12.类型断言
let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length; console.log(strLength)
let someValue: any = "this is a string"; let strLength: number = (someValue as string).length;
console.log(strLength)