TypeScript

  • ts是js类型的超集

为什么我们项目中要使用ts

  • js是弱类型【数据类型可改】脚本语言,就是稳定度、安全度较低
  • ts是强类型【数据类型不可改】脚本语言
  • ts可以编译代码的阶段就会发现错误,不需要去浏览器中预览错误 ,节省很多的调试代码的时间
  • ts可以提供给我们更多的语法提示
  • 不需要做属性校

安装编译

  • cnpm i typescript -g

快速的ts编译

  • tsc —init 生成 tsconfig.json 配置文件
  • 在配置文件 找到 outDir(编译后的js文件目录) 和 rootDir(ts文件目录),填写好相应的路径
    • 如 : “outDir”: “./dist”, “rootDir”: “./src”,
  • tsc 编译

ts文件中写什么?

  • ts中写的还是js,但是需要添加数据类型
  • 可以更高的es语法
  1. @test
  2. class App {
  3. }
  4. // 需要在tsconfig.json 配置文件中打开 "experimentalDecorators": true,

基本数据类型

  • 格式:let/const 变量名: 变量类型? = 变量值
  • number
  1. let n: number = 100;
  2. let m = 200; // 简写 ---> 类型推论:通过变量值来推断变量的数据类型
  3. m = 300;
  4. // m="100";报错
  • string
  1. let str: string = "hello ts";
  2. let s = "hello";
  3. s = "a";
  4. // s=100;报错
  • boolean
  1. let bol: boolean = true;
  2. let b = false;
  • undefined
  1. let und: undefined = undefined;
  2. let u = undefined;
  • null
  1. let nul: null = null;
  2. let nu = null;

对象类型

  • 如何类约定对象的数据类型呢? 提供了2种做法:interface[接口] type
  1. const obj: ObjType = {
  2. id: 1, // 只读
  3. name: "lilili" // 必须
  4. // age:22 // 可选
  5. };
  6. // interface接口写法
  7. interface ObjType {
  8. readonly id: number; // 只读属性
  9. name: string; // 必须属性
  10. age?: number; // 可选属性
  11. [propName: string]: any; // 任意属性【不能随意使用】
  12. }
  13. // type写法
  14. interface ObjType {
  15. // 里面写的同 interface 里面的一样
  16. }

数组

  • 普通数组
  1. // string型数组
  2. const arr: number[] = [1, 2, 3];
  3. arr.push(4);
  4. // arr.push("5");// 报错
  5. // number型数组
  6. const arr2: string[] = ["a", "b", "c"];
  7. arr2.push("d");
  8. // 联合类型
  9. const arr3: (number | string)[] = ["a", 1, "b", 3];
  10. // json数组
  11. const arr4: MovieType[] = [
  12. {
  13. a: 123,
  14. b: "456"
  15. },
  16. {
  17. a: 789,
  18. b: "123"
  19. },
  20. ]
  21. // 二维数组
  22. const arr5: (number | string)[][] = [
  23. [1, 2, 3],
  24. ["a", "b", "c"]
  25. ];
  26. // 比较复杂的数组类型
  27. const arr6: ((string | number)[] | MovieType)[] = [
  28. ["a", "b", "c"],
  29. [1, 2, 3],
  30. {
  31. a: 123,
  32. b: "456"
  33. }
  34. ]
  35. interface MovieType{
  36. a: number,
  37. b: string
  38. }

元组类型

  • 元组是一种特殊的数组
  • 规定了数组长度
  • 规定数组中元素的数据类型
  1. let items:[number,string]; // 规定这个数组长度是2,里面第一个元素是number,第二个是string类型
  2. items=[100,"hehe"];
  3. // items=[100,200];// 报错
  4. // items=[100,"hehe","lili"];// 报错

枚举

  • 枚举 => 遍历
  1. // 从1开始自动编号
  2. enum Hehe {'张三'=1,'李四','王二麻子'}
  3. console.log(Hehe[1]);// 张三
  4. console.log(Hehe["李四"]);// 2

函数

  • 需要定义参数类型和返回值类型
  1. // todo 1
  2. function fn (a:string,b:number):string{
  3. return "hello"
  4. }
  5. // todo 2
  6. const fn2 =(a:string,b:number):boolean=>{
  7. return true
  8. }
  9. // todo 3
  10. const fn3:(a:number,b:string)=>boolean=(a,b)=>{
  11. return true
  12. }
  13. // todo 4 --- 使用率最高
  14. const fn4:Fn4Type =(a,b)=>{
  15. return true
  16. }
  17. interface Fn4Type{
  18. (a:number,b:string):boolean
  19. }

内置对象类型