一、基本类型
1、ES6的数据类型
ES6的数据类型 | TypeScript的数据类型 |
---|---|
Boolean | void |
Number | any |
String | never |
Array | 元组 |
Function | 枚举 |
Object | 高级类型 |
Symbol | |
Undefined | |
Null |
2、类型注解
-
作用:相当于强类型语言中的类型声明
-
语法:(变量/函数): type
-
说明:它就是在函数或者变量后面加个冒号声明 类型
-
代码:
-
原始类型
//原始类型 let bool: boolean = true; let num: number = 123; let str: string = "123"
-
数组
//数组 let arr1: number[] = [1,2,3] let arr2: Array<number> = [1,2,3] //泛型接口 let arr3: Array<number | string> = [1,2,3,'4'] //联合类型 let arr3 = [1,2,4,'3'];
-
元组
//元组 它限定了数组的类型和个数 let tuple: [number, string] = [1, '2'] tuple.push(2) console.log(tuple) //tuple[2] 报错 不允许我们越界访问
-
函数
//函数 let add = (x: number, y:number):number => x + y let compute: (x: number, y:number) => number //没有具体实现 //实现 compute = (a, b) => a + b compute = (a, b) => { let c:any = 1; return a + b + c }
-
symbol
//symbol 具有唯一的值 let s1: symbol = Symbol() let s2 = Symbol() console.log(s1 === s2); //false //null和undefined 可以给变量声明为 let un: undefined = undefined //不可以赋值其它类型 只能赋值undefined let nu: null = null num = undefined // 修改配置文件tsconfig.json "strictNullChecks": false, num = null
-
void
//void 没有任何返回值的函数 它的类型就是void类型 let noReturn = () => {}
-
any 类型 任意类型
//any 任意类型的值 let x x = 1 x = [] x = () => {}
-
never 没有返回值的类型
//never 永远没有返回值的类型 let error = () => { throw new Error("error"); }
-