TypeScript
为什么我们项目中要使用ts
- js是弱类型【数据类型可改】脚本语言,就是稳定度、安全度较低
- ts是强类型【数据类型不可改】脚本语言
- ts可以编译代码的阶段就会发现错误,不需要去浏览器中预览错误 ,节省很多的调试代码的时间
- ts可以提供给我们更多的语法提示
- 不需要做属性校
安装编译
快速的ts编译
- tsc —init 生成 tsconfig.json 配置文件
- 在配置文件 找到 outDir(编译后的js文件目录) 和 rootDir(ts文件目录),填写好相应的路径
- 如 : “outDir”: “./dist”, “rootDir”: “./src”,
- tsc 编译
ts文件中写什么?
- ts中写的还是js,但是需要添加数据类型
- 可以更高的es语法
@testclass App {}// 需要在tsconfig.json 配置文件中打开 "experimentalDecorators": true,
基本数据类型
- 格式:let/const 变量名: 变量类型? = 变量值
- number
let n: number = 100;let m = 200; // 简写 ---> 类型推论:通过变量值来推断变量的数据类型m = 300;// m="100";报错
let str: string = "hello ts";let s = "hello";s = "a";// s=100;报错
let bol: boolean = true;let b = false;
let und: undefined = undefined;let u = undefined;
let nul: null = null;let nu = null;
对象类型
- 如何类约定对象的数据类型呢? 提供了2种做法:interface[接口] type
const obj: ObjType = { id: 1, // 只读 name: "lilili" // 必须 // age:22 // 可选};// interface接口写法interface ObjType { readonly id: number; // 只读属性 name: string; // 必须属性 age?: number; // 可选属性 [propName: string]: any; // 任意属性【不能随意使用】}// type写法interface ObjType { // 里面写的同 interface 里面的一样}
数组
// string型数组const arr: number[] = [1, 2, 3];arr.push(4);// arr.push("5");// 报错// number型数组const arr2: string[] = ["a", "b", "c"];arr2.push("d");// 联合类型const arr3: (number | string)[] = ["a", 1, "b", 3]; // json数组const arr4: MovieType[] = [ { a: 123, b: "456" }, { a: 789, b: "123" },]// 二维数组const arr5: (number | string)[][] = [ [1, 2, 3], ["a", "b", "c"]];// 比较复杂的数组类型const arr6: ((string | number)[] | MovieType)[] = [ ["a", "b", "c"], [1, 2, 3], { a: 123, b: "456" } ]interface MovieType{ a: number, b: string}
元组类型
- 元组是一种特殊的数组
- 规定了数组长度
- 规定数组中元素的数据类型
let items:[number,string]; // 规定这个数组长度是2,里面第一个元素是number,第二个是string类型items=[100,"hehe"];// items=[100,200];// 报错// items=[100,"hehe","lili"];// 报错
枚举
// 从1开始自动编号enum Hehe {'张三'=1,'李四','王二麻子'}console.log(Hehe[1]);// 张三console.log(Hehe["李四"]);// 2
函数
// todo 1function fn (a:string,b:number):string{ return "hello"}// todo 2const fn2 =(a:string,b:number):boolean=>{ return true}// todo 3const fn3:(a:number,b:string)=>boolean=(a,b)=>{ return true}// todo 4 --- 使用率最高const fn4:Fn4Type =(a,b)=>{ return true}interface Fn4Type{ (a:number,b:string):boolean}
内置对象类型